0

This code gives me an error:

$post = Post::find($post_id);
$post->deleted_at = null;
$post->save();

Here's the error:

Creating default object from empty value

Also tried

$post->deleted_at = '';

Which gave me the same error.

2 Answers 2

3

If it does not find the model you'll have null in that variable, so you can:

$post = Post::findOrNew($post_id); /// If it doesn't find, it just creates a new model and return it

$post->deleted_at = null;

$post->save();

But if you really need it to exist:

$post = Post::findOrFail($post_id); /// it will raise an exception you can treat after

$post->deleted_at = null;

$post->save();

And, if it just doesn't matter:

if ($post = Post::find($post_id)) 
{
    $post->deleted_at = null;

    $post->save();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Wasn't aware of those two functions.
1

You have to make sure that you successfully found the database record you are looking for. The error comes from you trying to access a database column on a null object.

A simple check will avoid your error:

$post = Post::find($post_id);

if ($post !== null) {
    $post->some_date_field = null;
    $post->save();
}

1 Comment

That's it. Thanks. I was trying to return a record that had been soft deleted. This would solve it for me: Post::withTrashed()->find($post_id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.