06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent: Relationships 601<br />

1 // Detach a single role from the user...<br />

2 $user->roles()->detach($roleId);<br />

3<br />

4 // Detach all roles from the user...<br />

5 $user->roles()->detach();<br />

For convenience, attach and detach also accept arrays of IDs as input:<br />

1 $user = App\User::find(1);<br />

2<br />

3 $user->roles()->detach([1, 2, 3]);<br />

4<br />

5 $user->roles()->attach([1 => ['expires' => $expires], 2, 3]);<br />

Updating A Record On A Pivot Table<br />

If you need to update an existing row in your pivot table, you may use updateExistingPivot<br />

method:<br />

1 $user = App\User::find(1);<br />

2<br />

3 $user->roles()->updateExistingPivot($roleId, $attributes);<br />

Syncing For Convenience<br />

You may also use the sync method to construct many-to-many associations. The sync method<br />

accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array<br />

will be removed from the intermediate table. So, after this operation is complete, only the IDs in the<br />

array will exist in the intermediate table:<br />

1 $user->roles()->sync([1, 2, 3]);<br />

You may also pass additional intermediate table values with the IDs:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!