eaponz
eaponz

Reputation: 604

Multi auth authorization error

My problem is I do have a multi-auth in Laravel, what I am trying to do is to have an authorization to this model App\Models\Admin instead of App\User

in my policy

class AdminsPolicy
{
    use HandlesAuthorization;

    public function view(\App\Models\Admin $admin)
    {
        return in_array($admin->role, [2,3,4]);

    }
}

now whenever I do something like this in my controller

dd(Auth::guard('admin')->user()->can('view'));

it always return false even if my admin role is correct

Upvotes: 0

Views: 101

Answers (1)

shock_gone_wild
shock_gone_wild

Reputation: 6740

Usually the Policies in Laravel are somehow tied to a specific resource. When using a policy you have to register it in your AuthServiceProvider like this

/**
 * The policy mappings for the application.
 *
 * @var array
 */
protected $policies = [
    Post::class => PostPolicy::class,
];

As you can see, the Policy is tied to a Post model in this example.

If you want to check, if a user can 'view' a specific post you have to pass that model as second paramter:

if($user->can('view', $post) { ... }

// or if you don't need a specific instance : 
if($user->can('create', Post::class) { ... } 

Maybe you are in fact looking for a Gate

You could define in your AuthServiceProviders boot function something like this:

    Gate::define('view', function(\App\Models\Admin $admin) {
        return in_array($admin->role, [2,3,4]);
    });

Upvotes: 1

Related Questions