Home > Enterprise >  How to use variable in Laravel Query Builder with if variable is not null
How to use variable in Laravel Query Builder with if variable is not null

Time:10-09

Hi I have a situation where I want

$first_name = $request->first_name;
$last_name = $request->last_name;

$customers = Customer::where('first_name','=',$first_name)
    ->where('last_name','=',$last_name **OR $last_name <> NULL**)
    ->get();

I want where clause to be implemented only if the input $last_name is not blank.

How can I achieve that?

CodePudding user response:

You can use when()

An example

$first_name = $request->input('first_name');
 
$customers = Customer::when($first_name, function ($query, $first_name) {
                    $query->where('first_name', $first_name);
                })
                ->get();

when will add where condition when the first_name is not NULL or false

I hope this helps you

CodePudding user response:

You can use :

$customers = Customer::where('first_name',$first_name)
    ->where(function ($q) use($last_name) {
    if ($last_name) {
       $q->where('last_name', $last_name);
    }
    })->get();
  • Related