Method in Policies does not return button for user of type Administrator

I’m having trouble displaying the Show in dojo.blade.php button only for admins (role === 1) in my showAdmin() in the UserPolicies.php file, even though it’s a admin type user the button is not visible to me.

  • UserPolicies.php
<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function showAdmin(User $user){
        return $user->role === 1;
    }
}
  • DojoController.php
    public function show($id)
    {
        $dojo = DojoModel::find($id);
        $this->authorize('showAdmin', Auth::user());
        $fighter = FighterModel::get(['id','name']);
        $master = MasterModel::get(['id','name']);
        return view('dojo.show', compact(['dojo','fighter','master']));
    }
  • dojo.blade.php
@can('showAdmin')
    <a href="{{ url("show-dojo/$d->id") }}" class="btn btn-warning"><i class="fa fa-eye"></i>&nbsp;Show</a>
@endcan

What would be the problem?

>Solution :

You also need to put the model :

@can('showAdmin', \App\Model\User::class)

or

@can('showAdmin', auth()->user())

also make sure to register the policy in AuthServiceProvider.php put it inside the protected $policies which is acccept the Model as a key and the Policy as its value

protected $policies = [
    User::class => UserPolicy::class,
]

Authorization in Blade file

Registering the policies

Leave a Reply