Categories
Uncategorized

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:

  1. Create a migration for the pivot table:
php artisan make:migration create_operating_unit_stakeholder_table
  1. 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();
});
  1. Run the migration to create the pivot table:
php artisan migrate
  1. Define the relationship in the OperatingUnit model:
class OperatingUnit extends Model
{
    public function stakeholders()
    {
        return $this->belongsToMany(Stakeholder::class)->withTimestamps();
    }
}
  1. Define the relationship in the Stakeholder model:
class Stakeholder extends Model
{
    public function operatingUnits()
    {
        return $this->belongsToMany(OperatingUnit::class)->withTimestamps();
    }
}
  1. To retrieve the stakeholders for an operating unit, you can use the stakeholders relationship:
$operatingUnit = OperatingUnit::find(1);
$stakeholders = $operatingUnit->stakeholders;
  1. 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);
  1. 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

Your email address will not be published. Required fields are marked *