user3684098
user3684098

Reputation: 389

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?

Upvotes: 0

Views: 523

Answers (2)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

Use below syntax to get user departments :

$user->departments;  

to insert :

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

to remove :

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

and for sync :

$arr=array(13,25,12);
$user->departments()->sync($arr);

Upvotes: 0

Mark Walet
Mark Walet

Reputation: 1186

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.

Upvotes: 0

Related Questions