Search code examples
laraveleloquentsoft-delete

Laravel Soft Delete restore() Error


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.


Solution

  • 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...