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...