Hosserin Ibrahim
Hosserin Ibrahim

Reputation: 224

use Auth for checking permission in spatie lara permission

I'm use Laravel 9. when I'm use permission checking by Auth Like:

Auth::user()->can('permission_name');

or

auth()->user()->hasPermissionTo('permission_name')

the program return error: Undefined method 'can'.intelephense(1013).

now I'm use:

$user = User::find(Auth::id());
$user->can('permission_name');

if there is better way a lot thanks if you tell me.

Upvotes: 0

Views: 1350

Answers (1)

Existed Mocha
Existed Mocha

Reputation: 168

As far as I know, the better way to implement permission is using Middleware

but you can use just like this, on every function with Request parameter

$request->user()->can('my-permission')

So if you using middleware, On the handle function in middleware you can pass a parameter that contain the permission

public function handle($request, Closure $next, $permission = null)
{
    if ($permission !== null && !$request->user()->can($permission)) {
        abort(404);
    }

    return $next($request);
}

and on the route you can pass the parameter to the middleware like this

Route::put('/post/{id}', 'TheControllerPath')->middleware('your_registered_middleware_name:my-permission');

Upvotes: 2

Related Questions