what about
Media::where('created_at', '<=', $delete_after_x_days)
->where(function ($query) {
$query->where('last_viewed_at', '<=', $delete_after_x_days)
->orWhereNull('last_viewed_at');
})
->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi everyone!
I have a small issue. I am trying to delete all entries which have not been viewed in the past 30 days and were created more than 30 days ago.
The column last_viewed_at's default value is null, so in case the entry was created_at 5 days ago and was not viewed, the row should get not be deleted.
I currently use
$medias = Media::where('created_at', '<=', $delete_after_x_days)
->where('last_viewed_at', '<=', $delete_after_x_days)
->orWhere('last_viewed_at', null)
->get();
This code snippet does not work, because it would also match entries that were created within the last 30 days but there last_viewed_at value is null.
Somehow, I think I need to have a nested if query that checks first if last_viewed_at has a value.
Any help would be greatly appreciated!
Thanks so much!
Chris
what about
Media::where('created_at', '<=', $delete_after_x_days)
->where(function ($query) {
$query->where('last_viewed_at', '<=', $delete_after_x_days)
->orWhereNull('last_viewed_at');
})
->get();
Please or to participate in this conversation.