Search code examples
laravelmany-to-manypivotpivot-table

Laravel many to many relationship with pivot table


if I try the following the page is loading endless:

$user_departments = User::find(1)->departments();

There are the following tables: - users - user_department - departments

The pivot table user_department has got this two foreign keys: - department_id - user_id

In my user model:

public function departments()
{
    return $this->belongsToMany('App\Department', 'user_department', 'user_id', 'department_id')->withTimestamps();
}

In my department model:

public function users()
{
    return $this->belongsToMany('App\User', 'user_department', 'department_id', 'user_id')->withTimestamps();
}

By the way: The following code is working:

$user->departments()->syncWithoutDetaching($department->id);

But I can't get the departments of the user without breaking my page.

Any ideas?


Solution

  • When fetching the departments of a user. You should actually get() the results. With $user->departments() you are getting the query builder which isn't a collection of results.

    Alternatively of using the get() method ($user->departments()->get()) You could use a shortcut: $user->departments.