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

mrweb's avatar
Level 1

Eloquent hasMany filtering the latest

I have an Order model and a OrderStatus Model.

I want to retrive for each order the last order status so this is what I do:

public function status()
{
    return $this->hasOne(OrderStatus::class, 'order_id', 'id')->latest();
}

Now, actually an Order can have more than one status, so I'm trying to figure out an Eloquent relation to show only those orders with a status of 1.

I tried an hasMany with a latest() but the problem is that I cannot filter it.

While if I have 4 Orders, each with 3 statuses and I need to filter only those on (latest) status = 0 It shows all of them because all have a status 0 while I need those with a status 0 only as their last status.

How do I achieve that with Eloquent?

0 likes
2 replies
vnvdv91's avatar

You can try this,

public function status()
{
    return $this->hasMany(OrderStatus::class);
}

$model->status()->where('status', 1)->get();

Please or to participate in this conversation.