Your cart is currently empty!
How to Create an Eloquent Relationship with Pivot Table in Laravel
To create an eloquent relationship for OperatingUnit has many Stakeholder with a pivot table in the middle in Laravel, follow the steps below:
- Create a migration for the pivot table:
php artisan make:migration create_operating_unit_stakeholder_table
- In the migration file, define the schema for the pivot table:
Schema::create('operating_unit_stakeholder', function (Blueprint $table) {
$table->id();
$table->foreignId('operating_unit_id')->constrained();
$table->foreignId('stakeholder_id')->constrained();
$table->timestamps();
});
- Run the migration to create the pivot table:
php artisan migrate
- Define the relationship in the OperatingUnit model:
class OperatingUnit extends Model
{
public function stakeholders()
{
return $this->belongsToMany(Stakeholder::class)->withTimestamps();
}
}
- Define the relationship in the Stakeholder model:
class Stakeholder extends Model
{
public function operatingUnits()
{
return $this->belongsToMany(OperatingUnit::class)->withTimestamps();
}
}
- To retrieve the stakeholders for an operating unit, you can use the
stakeholders
relationship:
$operatingUnit = OperatingUnit::find(1);
$stakeholders = $operatingUnit->stakeholders;
- To add a stakeholder to an operating unit, you can use the
attach
method:
$operatingUnit = OperatingUnit::find(1);
$stakeholder = Stakeholder::find(1);
$operatingUnit->stakeholders()->attach($stakeholder);
- To remove a stakeholder from an operating unit, you can use the
detach
method:
$operatingUnit = OperatingUnit::find(1);
$stakeholder = Stakeholder::find(1);
$operatingUnit->stakeholders()->detach($stakeholder);
Note: Laravel assumes the pivot table name by the singular name of the related models in alphabetical order. If you need to change the pivot table name, you can specify it as a second argument to the belongsToMany
method.
Leave a Reply