Laravel roles with Spatie package

1.3k Views Asked by At

How can I set a rule to user to prevent him entering specific route?

I added a column to permissions table name route and enter routes manually and I made a middleware but the problem is that all my controllers are resource so there is a lot of routes, so what is the best practice to do that?

public function handle($request, Closure $next)
{
    $routeName = $request->route()->getName();  //users.create
    $permission = Permission::whereRaw("FIND_IN_SET('$routeName',routes)")->first();  //find route
    if($permission)
    {
        if(!$request->user()->can($permission->name))
        {
            abort(403);
        }
    }
    return $next($request);
}
1

There are 1 best solutions below

0
On

You can use a middleware to protect routes.

You can group the routes like this:

Route::group(['middleware' => ['can:publish articles']], function () {
    //
});

Or you can protect the routes on the controller like this:

public function __construct()
{
    $this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}

For information here: https://spatie.be/docs/laravel-permission/v3/basic-usage/middleware