Test Human
Test Human

Reputation: 31

Laravel execute where condition based on variable null or not

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
}

Upvotes: 1

Views: 2956

Answers (2)

IGP
IGP

Reputation: 15786

Use Conditional Clauses

Model::when($search !== null, function ($query) use ($search) {
    return $query->where('column', $search);
})

Upvotes: 3

lagbox
lagbox

Reputation: 50481

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);
}

Upvotes: 0

Related Questions