Asif Mushtaq
Asif Mushtaq

Reputation: 3798

How to create extra relation in pivot table in laravel

I have following tables,

I can get the diplomas of users by defining this relation in User class.

public function diplomas(){
   return $this->belongsToMany(Diploma::class);
}

How I can get diplomas of users with the invoices? $user->diploma->pivot->invoice?

Upvotes: 0

Views: 53

Answers (1)

Patrick Schocke
Patrick Schocke

Reputation: 1491

You need to define an extra pivot model that holds the relation: https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models

public function diplomas(){
   return $this
        ->belongsToMany(Diploma::class)
        ->using(DiplomaUser::class)
        ->withPivot('invoice_id');
}

and your DiplomaUserClass:

class DiplomaUser extends Pivot
{
    public function invoice() {
        return $this->belongsTo(Invoice::class)
    }
}

Now you can do $user->diplomas->first()->pivot->invoice

Upvotes: 1

Related Questions