How to use correctly Super Admin's role in Laravel Spatie

8.8k views Asked by At

As it's write in doc, i used Laravel's Gate::before() method.

use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        // Implicitly grant "Super Admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability) {
            return $user->hasRole('Super Admin') ? true : null;
        });
    }
}

But it doesn't work. I had the role in middleaware groupe in web.php and it's work. The role 'Super Admin' dont have any permission.

Route::group(['middleware' => ['auth:api','role:Super Admin|Provider']], function() {
  ...
}

In my ProviderController

class ProviderController extends Controller
{
    function __construct(){
       
        $this->middleware('permission:provider-list|provider-create|provider-edit|provider-delete', ['only' => ['index','show']]);
        $this->middleware('permission:provider-create', ['only' => ['create','store']]);
        $this->middleware('permission:provider-edit', ['only' => ['edit','update']]);
        $this->middleware('permission:provider-delete', ['only' => ['destroy']]);
        
    }

My question it's the right way or not ? I thank you in advance.

2

There are 2 answers

6
Yinci On

We use Spatie/laravel-permission often (docs). Your code for checking if a user has a role is correct. Spatie's hasRole function does not care for spaces or dashes. The function does however care for whether the role actually exists. Ensure you migrated the right tables, and actually inserted the role into your database.

\Spatie\Permission\Models\Role::create([
  'name' => 'Super Admin',
  'guard_name' => 'web',
]);

$user->assignRole(\Spatie\Permission\Models\Role::findByName('Super Admin'));
0
Ricardo Alejandre On

Your issue is likely that you only inserted the role for the web guard. You probably have it as the default guard, and that was the one inserted in your migration. The issue is that you are using the api guard to access that route. So you have to create the role for that guard too. I think they mention that in the Spatie documentation.