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

Albertiss's avatar

make query with if condition in controller

i have 3 tableles, i want to make a join query, but i want use if condition to check if the value of input sent in $request from the form if it''s not null i want to add whele contition:

my request is:

  $query = DB::table('state')
        ->join('merchant','state.merchant_id', '=', 'merchant.id') 
        ->join('entity','state.entity_id', '=', 'entity.id')  
         ->where('state.entity_id', '=', 'value of idinput')// to use if condition here
         ->where('merchant_name, '=', 'value of nameinput')// to use if condition here
         ->where('entity_color', '=', 'value of colorinput')// to use if condition here
        ->select('*')
        ->get();
0 likes
5 replies
Tray2's avatar

The easy way to get help is to wrap any code blocks with three back ticks ` to make it readable.

I suggest checking that if the value is present before running the query.

if (request has the sought after value) {
	run query with given value
} else {
	run another query without the value
}
Albertiss's avatar

@Tray2 i have 3 conditions but , if i use if conditidion, query doen't take it in my code, with conditions, if the input value is empty query will take it as null, i want to use just unuable values in query

wassimo's avatar

I think you are in a good way just make a condition based on your $request field or in one function like that:

private function filterByRelationship($query, $keyword, $relativeTables)
{
    foreach ($relativeTables as $relationship => $relativeColumns) {
        $query->orWhereHas($relationship, function($relationQuery) use ($keyword, $relativeColumns) {
            foreach ($relativeColumns as $key => $column) {
                $clause = $key == 0 ? 'where' : 'orWhere';
                $relationQuery->$clause($column, "LIKE", "%$keyword%");
            }
        });
    }

    return $query;
}

Please or to participate in this conversation.