Home > database >  $this->authorize('gate-name') in laravel 9 with 2 parameters
$this->authorize('gate-name') in laravel 9 with 2 parameters

Time:08-09

I'm learning authorization in laravel 9 using 'gate'. In my case, I want to protect my controller so who can access the controller only users who have "delete" and "edit" 'gate'.

Then I created 2 new gates in 'App\Providers\AppServiceProvider' defined as follows:

Gate::define('edit', function (User $user) {
    return $user->permission === 'edit';
});

Gate::define('delete', function (User $user) {
    return $user->permission === 'delete';
});

Then, I need to add $this->authorize('edit') and also $this->authorize('delete') in the controller, unfortunately it can't be done, laravel only accept once of $this->authorize('edit') or $this->authorize('edit'). The problem is, I have to add 2 conditions there, I also can't write an array as a parameter.

What I want is like this:

$this->authorize('edit' && 'delete')

Or:

$this->authorize(['edit', 'delete'])

Unfortunately, I can't add both. Basically, the user have to pass 2 checks (must have "edit" AND "delete' gate) using the laravel 'gate' feature in my controller.

The check is like this: "Does that user have edit access"? OR "Does that user have delete access"? if "yes/true", allow entry to the controller, else "return 403"

FOR EASIER EXAMPLES: I have this controller to delete a post on my web:

public function destroy(Post $post)
   {
       $this->authorize('edit'); // I want not only check 'edit', I want to check 'delete' too
       $post->delete();
   }

How to apply it?

I have checked this question but no answer

CodePudding user response:

You can use the Gate facade to interact with the authorization system and without throwing an exception (just checking gates):

if (Gate::check(['edit', 'delete'])) {
    // has all these permissions
} else {
    // does not have all these permissions
}
  • Related