can u help me pls? Added spatie/laravel-permission, everything works by middleware in routes/api.php
Route::get('roles', [RoleController::class, 'rolesIndex'])->middleware('role:Admin');
I wanted to make a role check for api and added a function:
function check($roleName) {
$user = Auth::user();
if (!$user->hasRole($roleName)) {
abort(403);
}
return response('', 202);
}
Added to the router - addressing the route:
Route::get('check/{roleName}', [RoleController::class, 'check']);
But when contacting me it gives: Call to a member function hasRole() on null
CodePudding user response:
To get the authenticated user
of your API
, you'll need to reference the api
guard:
$user = auth('api')->user();
if (!$user->hasRole($roleName) {
// ...
}
Or simpler still:
if (!auth('api')->user()->hasRole($roleName)) {
// ...
}