To relate the contracts and medical insurance, you can create a many-to-many relationship between the User model and the Contract and HealthInsurance models. You can create two pivot tables: user_contract and user_health_insurance.
In your User model, add the following methods:
public function contracts()
{
return $this->belongsToMany(Contract::class);
}
public function healthInsurances()
{
return $this->belongsToMany(HealthInsurance::class);
}
In your Contract model, add the following method:
public function users()
{
return $this->belongsToMany(User::class);
}
In your HealthInsurance model, add the following method:
public function users()
{
return $this->belongsToMany(User::class);
}
Create two pivot tables using migrations:
php artisan make:migration create_user_contract_table --create=user_contract
php artisan make:migration create_user_health_insurance_table --create=user_health_insurance
In the create_user_contract_table migration, add the following code:
Schema::create('user_contract', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('contract_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('contract_id')->references('id')->on('contracts')->onDelete('cascade');
$table->primary(['user_id', 'contract_id']);
});
In the create_user_health_insurance_table migration, add the following code:
Schema::create('user_health_insurance', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('health_insurance_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('health_insurance_id')->references('id')->on('health_insurances')->onDelete('cascade');
$table->primary(['user_id', 'health_insurance_id']);
});
Finally, you can access the contracts and health insurances of a user using the contracts and healthInsurances methods:
$user = User::find(1);
$contracts = $user->contracts;
$healthInsurances = $user->healthInsurances;