Laravel 5.4 Zizaco/entrust - user soft delete

566 Views Asked by At

How can I prevent detaching of roles on user soft delete?
$user->hasRole('subscriber') => true
$user->delete()
$user->hasRole('subscriber') => false
$user->restore()
$user->hasRole('subscriber') => false

1

There are 1 best solutions below

0
On

Look at EntrustUserTrait rows 69-80.

/**
 * Boot the user model
 * Attach event listener to remove the many-to-many records when trying to delete
 * Will NOT delete any records if the user model uses soft deletes.
 *
 * @return void|bool
 */
public static function boot()
{
    parent::boot();
    static::deleting(function($user) {
        if (!method_exists(Config::get('auth.model'), 'bootSoftDeletes')) {
            $user->roles()->sync([]);
        }
        return true;
    });
}

I think you do not use Laravel's own SoftDeletes trait if you have not bootSoftDeletes.

class User extends Authenticatable
{
    use SoftDeletes;
    use EntrustUserTrait;
    ...