0

here I have a code that I query inside a relationship that I want just 1 part to be executed if the user send the variable to me if not that query didn't run at all here is my code I commented in my code where I want my condition:

$bed_count = $request->get('bed_count');
$data = Accommodation::with(['city','accommodationRoomsLimited.roomPricingHistorySearch' =>function($query) use($from_date,$to_date){
$query->whereDate('from_date', '<=', $from_date);
                    $query->whereDate('to_date', '>=', $to_date);
         },'accommodationRoomsLimited' => function($q) use($bed_count){
          //here is I want my query to be executed if the user sends bed_count if not the code should skip this part
          $q->orWhere('bed_count',$bed_count);
        }])

1 Answer 1

2

Not clear what are you trying to achieve.

  1. If you want to eager load accommodationRoomsLimited all the time,
    But when user has provided bed count, you need to filter those accommodationRoomsLimited with this bed count.

If that's so

$bed_count = $request->get('bed_count');

$data = Accommodation::with([
    'city',
    'accommodationRoomsLimited.roomPricingHistorySearch' => function($query) use($from_date,$to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    },
    'accommodationRoomsLimited' => function($q) use($bed_count) {
        if ($bed_count) {
            $q->where('bed_count',$bed_count);
        }
    }
]);
  1. If you only want to eager load accommodationRoomsLimited only when user has provided bed count.

Then

$bed_count = $request->get('bed_count');

$data = Accommodation::with([
    'city',
    'accommodationRoomsLimited.roomPricingHistorySearch' => function($query) use($from_date,$to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    },
])
->when($bed_count, function ($query, $bed_count) {
    $query->with([
        'accommodationRoomsLimited' => function($q) use($bed_count) {
            $q->where('bed_count',$bed_count);
        }
    ]);
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks that saved me time !!! is when telling the query to load when the bedcount is given by user ??
Yes when() function first parameter is a condition, second parameter is what to do when condition passes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.