Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

earmsby's avatar

Relationship with same table

I'm trying to figure out the best way to write an eloquent relationship between a table (contracts) and itself. I need to be able to associate a contract with another contract. I think it would be similar to a pivot table scenario but I'm getting tied up in the syntax. Any advice?

0 likes
1 reply
LaryAI's avatar
Level 58

To create a self-referential relationship in Eloquent, you can use a "many-to-many" relationship with a pivot table. This is useful when you want to associate a contract with other contracts. Here's how you can set it up:

  1. Create a Pivot Table:

    First, create a migration for the pivot table. This table will store the associations between contracts.

    php artisan make:migration create_contract_contract_table --create=contract_contract
    

    In the migration file, define the table structure:

    Schema::create('contract_contract', function (Blueprint $table) {
        $table->id();
        $table->foreignId('contract_id')->constrained('contracts')->onDelete('cascade');
        $table->foreignId('related_contract_id')->constrained('contracts')->onDelete('cascade');
        $table->timestamps();
    });
    

    Run the migration:

    php artisan migrate
    
  2. Define the Relationship in the Model:

    In your Contract model, define a many-to-many relationship to itself:

    use Illuminate\Database\Eloquent\Model;
    
    class Contract extends Model
    {
        public function relatedContracts()
        {
            return $this->belongsToMany(Contract::class, 'contract_contract', 'contract_id', 'related_contract_id');
        }
    }
    

    This method relatedContracts will allow you to access all contracts related to a given contract.

  3. Using the Relationship:

    You can now use this relationship to associate contracts with each other:

    // Assuming you have two contract instances
    $contract1 = Contract::find(1);
    $contract2 = Contract::find(2);
    
    // Attach a related contract
    $contract1->relatedContracts()->attach($contract2->id);
    
    // Retrieve related contracts
    $relatedContracts = $contract1->relatedContracts;
    

This setup allows you to associate contracts with each other using a pivot table, similar to a many-to-many relationship. You can attach, detach, and sync related contracts as needed.

2 likes

Please or to participate in this conversation.