79543093

Date: 2025-03-29 10:22:33
Score: 0.5
Natty:
Report link

The problem is your middleware is called before authorisation:

    Route::get('/log'...)->middleware('view-logs');

will not work, while this will

Route::group(['middleware' => [auth:api]], function(){
    Route::get('/log'...)->middleware('view-logs');

})

Why it works?

With auth:api or even auth middleware the logged in user appears, while without this middleware you don't have logged in user and checking for Auth::check() will always be false. That is expected behaviour.

Can it be done even better?

Yes, if you are using spatie/laravel-permissions, and ->hasRole() make me think you are. Then you can get rid of self written middleware and use this.

Route::get('/log...', [...Controller::class, 'index'])->middleware('role:admin');
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Oleg