49

The following soft delete code works fine for me:

$post = Post::find($post_id);
$post->delete();

The deleted_at field is updated. But this gives me an error:

$post = Post::find($post_id);
$post->restore();

Here's the error:

exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function restore() on a non-object'

I'm stumped. Google is no help so far.

sterfry68
  • 1,063
  • 2
  • 14
  • 30

3 Answers3

111

Error says $post is a non-object, Laravel doesn't return trashed records without withTrashed()

Post::withTrashed()->find($post_id)->restore();

Laravel Docs - Soft Deleting

When querying a model that uses soft deletes, the "deleted" models will not be included...

Brian Dillingham
  • 9,118
  • 3
  • 28
  • 47
5

Another option is to search through the trashed models for a specific ID:

Post::onlyTrashed()->where('id', $post_id)->restore();
miken32
  • 42,008
  • 16
  • 111
  • 154
jak
  • 67
  • 1
  • 3
  • 1
    Review: Adding some comment and explanation with your answer would be nice. – H.Hasenack Jan 30 '21 at 20:28
  • khalid, is your insight here to point out that withTrashed is unnecessary when you know you're looking for trashed values? if so it could be good to clarify that. – lahwran Jan 30 '21 at 20:30
  • withTrashed use for recuperate post deleted and post not deleted ,onlytrashed use for recuperate only post deleted – jak Feb 02 '21 at 13:28
0

Maybe it will be of use to someone in the future. You can easily use restore when on the routing we also download with deleted ones.

Route::post('restore/{exampleModel}', [ExampleController::class, 'restore'])->withTrashed();
public function restore(ExampleModel $exampleModel)
{
        $exampleModel->restore();
}
Angir777
  • 1
  • 1