Andrew Andrew - 7 months ago 28
PHP Question

Add where clause to relations table in laravel

I have a question. This query gets me the needed data and that includes the related table

delivery


$RS = $this->instance->user()->with(['driver.trailer', 'driver.truck', 'driver.delivery']);


I researched this topic, and I think part below should do the trick, but I don't know how to combine the two together.

//add WHERE clause to driver.delivery:
->whereBetween('created_at', [
Carbon\Carbon::parse('last monday')->startOfDay(),
Carbon\Carbon::parse('next sunday')->endOfDay(),])
->get();


I am new to Laravel (doing it for about 10 days now) and this concept is very new to me. (I have no issues writing a standard query)

Answer

Try this:

return $this->instance->user()->with(['driver.delivery' => function($query){
        $query->whereBetween('created_at', [ 
            Carbon\Carbon::parse('last monday')->startOfDay(),
            Carbon\Carbon::parse('next sunday')->endOfDay() ]);
    }])->with(['driver.trailer' 'driver.truck'])->get();