To set up Spatie Permissions with Teams in Laravel 11, you'll need to follow these steps. Please note that the Spatie Permissions package may have updates, so always refer to the official documentation for the most accurate and up-to-date information.
- Install the Package: First, you need to install the Spatie Laravel Permission package via Composer.
composer require spatie/laravel-permission
-
Publish the Migration: After installing the package, you should publish the migration with the
--teamsflag to include the necessary columns for team support.
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="teams-migrations"
- Run the Migration: Once the migration is published, run it to create the required tables.
php artisan migrate
-
Configure the Models: You need to add the
HasRolestrait to your User model and specify that you're using teams.
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
protected $guard_name = 'web'; // or whatever guard you want to use
public function scopeCurrentTeam($query)
{
return $query->where('team_id', auth()->user()->current_team_id);
}
}
-
Set Up Teams: You'll need to create a Team model if you don't have one already. This model should use the
HasRolestrait as well.
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;
class Team extends Model
{
use HasRoles;
protected $guard_name = 'web'; // or whatever guard you want to use
}
-
Create Roles and Permissions: Now you can create roles and permissions with the
team_idproperty.
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$teamId = 1; // The id of the team
$role = Role::create(['name' => 'editor', 'team_id' => $teamId]);
$permission = Permission::create(['name' => 'edit articles', 'team_id' => $teamId]);
$role->givePermissionTo($permission);
- Assign Roles to Users: Assign the role to a user within a team context.
$user->assignRole('editor', $teamId);
- Middleware: If you want to use middleware to check permissions, you can do so by passing the team id.
Route::group(['middleware' => ['role:editor,' . $teamId]], function () {
// your routes
});
- Blade Directives: In your Blade templates, you can check for roles and permissions within a team context.
@role('editor', $teamId)
// The user has the editor role within the team context
@endrole
@can('edit articles', $teamId)
// The user has permission to edit articles within the team context
@endcan
Remember to replace $teamId with the actual team ID you want to check against. This is a basic setup, and depending on your application's needs, you might need to adjust or extend this setup. Always refer to the official Spatie Permission documentation for the latest information and advanced usage.