Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detach only the last record in the pivot table using detach() in Laravel 4?

If I do this:

return $this->roles()->detach($role);

all roles are removed.

How to limit that to only the last one?

like image 222
aspentistar Avatar asked Dec 19 '25 01:12

aspentistar


1 Answers

You can do it without timestamps:

$lastRole = $user->roles()
    ->orderBy( $user->roles()->getTable() .'id', 'desc')
    ->first();
$user->roles()->detach($lastRole);

or with timestamps:

$lastRole = $user->roles()->latest()->first();
$user->roles()->detach($lastRole);
like image 145
Jarek Tkaczyk Avatar answered Dec 20 '25 20:12

Jarek Tkaczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!