Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Raiserweb's avatar

hasMany relation using withTrashed(), add a 'only before' date

Laravel's soft deletes are useful. But I have a case that I am sure must be common. I need to display a trashed relationship, but only if the relation was deleted before a specific date, based on the parent.

My case is Events, and Seat Types. Events have many Seat Types. (eg 1 theatre event has standard seats, VIP seats, house seats)

When an event date is before the deleted_at date of a seattype, I want to relate the seat type to the event. When the deleted_at date of the seat types was after the event date, I don't want to pull the relation.

Any pointers on this would be great - perhaps this is not possible with Eloquent, since the where clause of the deleted_at will need to be different for each of the rows of the event table.

0 likes
4 replies
tykus's avatar

I believe this should work:

// Event.php

public function seats()
{
    return $this->hasMany(Seat::class)
        ->withTrashed()
        ->where(function ($query) {
            $query->whereNull('deleted_at') // it has not been deleted
                ->orWhere('deleted_at', '>', $this->date); // it was deleted after Event date 
        });
}
1 like
Raiserweb's avatar

Thanks @tykus for the help, but $this->date is not set in the relation function (this was my original try)

RonB1985's avatar

Do you mean $this->date is not accessible in the function? Try this:

// Event.php

public function seats()
{
    return $this->hasMany(Seat::class)
        ->withTrashed()
        ->where(function ($query) use ($this) {
            $query->whereNull('deleted_at') // it has not been deleted
                ->orWhere('deleted_at', '>', $this->date); // it was deleted after Event date 
        });
}
tykus's avatar

Yeah, my mistake... it is of course not available in an object context in a query scope.

Please or to participate in this conversation.