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

Hala's avatar
Level 3

Query depends on multi optional parameter

I have two optional parameter

and need to query them with condition how could be that ?

i used this ,but there is no relation return back with it

public function show(Request $request,$id, $languages= null,$destinations=null ) {

    $planner=Planner::findOrFail($id);



    if($languages){
        $planner->with('language');
    }

    if($destinations){
        $planner->with('destination');
    }

    return response()->json([
        'status' => $planner->get()
    ], 200);
}
0 likes
3 replies
Sergiu17's avatar

instead of ->with try load()

$planner = Planner::findOrFail($id);

if($languages){ 
  $planner->load('language');
}

if($languages){ 
  $planner->load('destination');
}

return response()->json([
  'data' => $planner,
], 200);

You don't need ->get() at the end, and change name of the key, it's not status, it's data or planners or plans whatever

1 like
Hala's avatar
Level 3

nope i can't get relation inside the condition and i don't know why even when the condition is true if i execute the relation outside the condition it will be fine

MichalOravec's avatar
Level 75

What about this:

$planner = Planner::when($languages, function ($query) {
    $query->with('language');
})->when($destinations, function ($query) {
    $query->with('destination');
})->findOrFail($id);

return response()->json([
    'planner' => $planner
], 200);
1 like

Please or to participate in this conversation.