Artek
Artek

Reputation: 57

Laravel policy always denies access

I registered policy

protected $policies = [
         'App\Grade' => 'App\Policies\GradesPolicy'

    ];

Thi is my route for this resource:

Route::get('/grades', 'GradesController@showGrades');

Controler method

public function showGrades()
    {

        $this->authorize('viewAny');

        switch(Auth::user()->role)
        {
            case 'teacher':
               return view('teacher');
            break;

            case 'parent':
              return view('parent');
            break;

            default:
             abort(400);
            break;
        }
    }

And policy method

public function viewAny(User $user)
    {

         return $user->check();
    }

Yes I know there are related topics here. I read them. I know this is something with model binding. The viewAny method is never invoked. I usedd dd inside of it and it shows nothing. But how am I supposed to bind model here? Any ideas?

Upvotes: 0

Views: 1358

Answers (1)

Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1743

you didn't specify the relevant model to the authorize method when calling the action "viewAny", so what you need to do is:

$this->authorize('viewAny',Grade::class);

or add it directly to the middleware and delete the authorize call from your controller

Route::get('/grades','GradesController@showGrades')
->middleware('can:viewAny,App\Grade');

Upvotes: 2

Related Questions