skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search