Chirica Andrei
Chirica Andrei

Reputation: 87

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.

Upvotes: 3

Views: 225

Answers (1)

OMR
OMR

Reputation: 12188

you can use with:

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

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

    }])->get();

Upvotes: 1

Related Questions