简体   繁体   中英

Eloquent restore() function on soft deletes failing to restore

I recently added soft deletes on my user model and the delete part of it works perfectly, however when I try to restore I get an error that says Call to a member function restore() on a non-object .

My code for restoring a soft deleted user is as follows:

public function putActivateUser()
    {
        $user = Emp::onlyTrashed()->where('id', '=', Input::get('actEmpId'))->first();
        $user->restore();

        return Redirect::route('user_data')
        ->with('message', 'Bruker '.$user->user_name.' aktivert.');
    }

The form for the user activation:

{{ Form::open(array('url' => 'bassengweb/ressurect_user', 'method' => 'PUT')) }} 
        {{ Form::select('actEmpId', $deactEmps) }}
        {{ Form::submit('Aktiver Bruker') }}
{{ Form::close() }}

A dd on $user returns null for some reason, but I can't see why.

尝试这个

Emp::withTrashed()->where('id','=',Input::get('actEmpId'))->restore();

Apparently user with id from the form is not found with onlyTrashed scope. You should check the query (run DB::getQueryLog() for example) and data in your db, but first change the method to firstOrFail :

$user = Emp::onlyTrashed()->where('id', '=', Input::get('actEmpId'))->firstOrFail();

It will throw ModelNotFoundException if nothing was found, so you can catch it and do whatever is needed, thus avoid calling method on null error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM