phpeloquentsoft-delete

Why is my entry only recognized only when I put ::withTrashed() on the model


So I am creating an user, on creation I set the deleted_at date a hour ahead so it softdeletes if the time passes, but the problem is that eloquent is already taking the entry as softdeleted.How do I fix this without making the deleted_at null.

This works:

$user = User::withTrashed()->where('id',15)->first();

And this does not:

$user = User::where('id',15)->first(); //returns null

This is my code for setting the deleted_at time on creation in the model file:

public static function boot()
{
    parent::boot();

    static::creating(function ($model) {
            $model->deleted_at = now()->addHour();
    });
}

Solution

  • Soft deletions aren't made for this; the date is simply a record of when it was deleted. Laravel's queries just look for a NULL value in deleted_at; nothing fancier.

    What you want is your own global scope you can apply to the model. You could use deleted_at in it, but you're probably better off with something like available_until to keep them separate.