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.
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();
}
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();
}
Post::withTrashed()->find($post_id);