Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to filter hasMany relation based on parameter?

I have a Restaurant Model :

class Restaurant extends Model
{
    public function orders()
    {
        return $this->hasMany('App\Order', 'id_restaurant');
    }

}

with a hasMany relation with Order.

What i want to do is to get Restaurant with Orders between some dates.

Restaurant::whereHas('orders' , function($q) use($startDate, $endDate){

                $q->where('created_at', '>=', $startDate->toDateTimeString())->where('created_at', '<=', $endDate->toDateTimeString());

            })

This is what i tried but is not good. In other words i want to filter the relation of a Model by some parameters.

like image 485
Chirica Andrei Avatar asked Dec 19 '25 09:12

Chirica Andrei


1 Answers

you can use with:

Restaurant::with(['orders'=>  function($q) use($startDate, $endDate){

        $q->whereBetweeen('created_at',  [$startDate,$endDate]);

    }])->get();
like image 191
OMR Avatar answered Dec 21 '25 22:12

OMR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!