0

I have defined a Policy named UserPolicy which goes like this:

class UserPolicy
{
    use HandlesAuthorization;

    public function edit(User $user)
    {
        if(Gate::allows('edit', $user)){
            return view('admin.users.edit' , compact('user'));
        }
        abort(403);
    }
}

And at AuthServiceProvider.php, I have called it like this:

protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
        User::class => UserPolicy::class
    ];

Then at the Blade, I added this:

@can('edit', $user)
   <a href="{{ route('users.edit' , ['user' => $user->id]) }}" class="btn btn-sm btn-primary">Edit</a>
@endcan

But now, I get this error:

Class 'App\Policies\Gate' not found

How can I fix this issue?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

Look like you have not imported Gate facade in UserPolicy class

use Illuminate\Support\Facades\Gate;
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • Great! But now I get `Maximum function nesting level of '256' reached, aborting! ` –  Jun 12 '21 at 06:01
  • see this answer https://stackoverflow.com/questions/8656089/solution-for-fatal-error-maximum-function-nesting-level-of-100-reached-abor – John Lobo Jun 12 '21 at 06:05
  • 1
    @tejoslaeslio your gate needs to return true or false to indicate if a user is authorised to perform a task. You're returning the view (which itself calls the gate again) – apokryfos Jun 12 '21 at 06:11
  • @apokryfos So what is the proper way –  Jun 12 '21 at 06:12
  • 1
    it depends what you need the gate to do. The idea is when you have the line `@can('edit', $user)` to deremine whether the current user can perform the `edit` action on the parameter `$user`. The gate needs to return `true` if the current user can edit `$user` and false otherwise. That really depends what your edit policy is. Maybe you need to check if the current user is the same as `$user` or if the current user is a user administrator or something like that – apokryfos Jun 12 '21 at 06:16