In this lesson, we will take care of the Teams DB structure.
In the previous lesson, we installed the Spatie Permissions package. Next, we must enable teams in the configuration file.
config/permission.php:
// ... 'teams' => true, // ...
Next, we create the Team Model and Migration.
php artisan make:model Team -mf
app/Models/Team.php:
use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Factories\HasFactory; class Team extends Model{ use HasFactory; protected $fillable = [ 'name', ];}
database/migrations/xxx_create_teams_table.php:
Schema::create('teams', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps();});
Also, let's define the factory, which will be used later in the tests.
database/factories/TeamFactory.php:
use Illuminate\Database\Eloquent\Factories\Factory; class TeamFactory extends Factory{ public function definition(): array { return [ 'name' => 'Clinic ' . fake()->word(), ]; }}
Users in Teams: Relationships
We need to implement two rules:
- User may belong to multiple teams (clinic owner)
- Only one team is active (current) at any point
First, let's create the second part, as it's easier. We will save the current team ID in the users table.
php artisan make:migration add_current_team_id_to_users_table
database/migrations/xxx_add_current_team_id_to_users_table.php:
Schema::table('users', function (Blueprint $table) { $table->foreignId('current_team_id') ->nullable() ->constrained('teams') ->nullOnDelete();});
And then the Model's fillable and relationship:
app/Models/User.php:
use Illuminate\Database\Eloquent\Relations\BelongsTo; class User extends Authenticatable{ // ... protected $fillable = [ 'name', 'email', 'password', 'current_team_id', ]; public function currentTeam(): BelongsTo { return $this->belongsTo(Team::class, 'current_team_id'); }
Now, with multiple teams, you might be tempted to...
This is a great tutorial. I'm trying to adapt to my Livewire Project. Thanks
If I need nested structure for team - would it work in Spatie Permissions teams?
Regarding
$user->assignRole(Role::MasterAdmin);you may wish to rather use$user->syncRoles([Role::MasterAdmin]);to ensure the user only has a single role, because multiple roles can be applied to the user which can lock or unlock areas of the site.For example, I would by default apply a User role (or Patient) then upgrade this to Admin/Manager/Owner. If it still had the User role then policies/traits/checks may exclude the admin from doing things if the checks are looking at the User role.
If you are doing a sole check based on the role - then that's right, this is an issue.
But if you were to do checks based on permissions - you wouldn't have that problem, since each role would extend permissions list