Search code examples
phplaraveleloquentmany-to-many

Laravel, Eloquent: Fetch all entries from many-to-many relation


I have two tables linked by a pivot table (with a custom migration):

Interest table:

ID | label

Person table:

ID | label

PersonHasInterest table (custom migration):

InterestID | PersonID | notes

How can I get all records from the pivot table (with persons and interests joined in)? I don't want to get all interests of a person or all persons that have an interest but all entries (with joins) of the pivot table.


Solution

  • Even though Pivot extends Model it is not possible to call the standard model functions on a Pivot-object. Issue on Github.

    What I came up is using the DB-Facade to execute a select statement, like so:

    DB::table('person_has_interest')
        ->join('interest', 'person_has_interest.interest_id', '=', 'interest.id')
        ->join('person', 'person_has_interest.person_id', '=', 'person.id')
        ->get(); // further manipulation like select possible