1

I am new to laravel. I want to execute my where condition if my variable value is not null. I tried the below code exactly not getting an idea of what to do.

$search = $array['search'];
$id = $array['id'];
$Data = Model::where('id', '=', $id)

if($search != '') {
    //I want to include where condition here
}
1
  • You wish to include filter based on id and search or from search only? Commented Feb 1, 2021 at 3:42

2 Answers 2

3

Use Conditional Clauses

Model::when($search !== null, function ($query) use ($search) {
    return $query->where('column', $search);
})
Sign up to request clarification or add additional context in comments.

4 Comments

$Data = DB::table('mytable')->where('id', '=', $Id) ->when(!is_null($searchBy) !== null, function ($query) use ($searchBy) { return $query->where('pid', '=', $searchBy)->orWhere('pname', 'like', '%' . $searchBy . '%')->orWhere('ps', 'like', '%' . $searchBy . '%'); })->get(); As per your answer, i build this query, but it didn't give me the appropriate result. My query should be like this select * from table where id=$id AND (pid = $searchby OR pname = $searchby OR ps = $searchby)
is_null($searchBy) !== null will always return false because is_null returns true or false. Either use when(is_null($search), ...) or when($search !== null, ...). Don't combine them.
Got it. Can i use multiple conditions in when like this Model::when($search !== null && $search >0, function ($query) use ($search) { return $query->where('column', $search); })
You can do whatever you want as long as it evaluates to a bool.
0

Your $Data variable is an Eloquent Query Builder object so you can add conditions to it for the query you are building:

if ($search) {
    $Data->where('field', $search);
}

Comments

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.