That is indeed a hasMany/belongsTo relationship (one-to-many). Add a client_id column of type foreignId to your user model (using a migration – make sure to make it nullable), then add the appropriate relationship functions to the user and client models, and voilà. That’s all yo need to do.
Assuming you’ve created your client model and the corresponding table, here’s what you do:
1. Create the migration for the relationship
> php artisan make:migration add_client_relation_to_users
// Or whatever you want to call the migration file
2. In the generated migration file, add the foreign ID column
return new class extends Migration {
public function up() {
Schema::table('users', function (Blueprint $table) {
$table->foreignId('client_id')->nullable()->cascadeOnUpdate()->nullOnDelete()->constrained();
$table->boolean('is_admin')->default(FALSE);
});
}
public function down() {
Schema::table('users', function(Blueprint $table) {
$table->dropColumn('client_id');
$table->dropColumn('is_admin');
});
}
};
This will add the column to your users table, make sure it references clients.id, cascade on update (so if for some reason a client’s ID changes, it will be updated in the user table as well), and set to null on delete (so if a client is deleted, the user remains, but becomes disassociated with any client).
(I’ve also added an is_admin column to actively keep track of administrators.)
3. In your models, add the appropriate relationship methods
class User extends Model {
public function client() {
return $this->belongsTo(Client::class);
}
}
class Client extends Model {
public function users() {
return $this->hasMany(User::class);
}
}
That’s it!