Vinod VT
Vinod VT

Reputation: 7159

Execute a where condition when search key is not null in Laravel query

I would like to run where condition on a select query only when the search key is not empty. If the search key is empty skip that where condition. This is my code,

$users =  User::orderBy('id','asc')
            ->join('agents', 'users.id', '=', 'agents.user_id')
            ->select('users.id', 'users.first_name', 'users.last_name', 'users.email')

            ->where('agents.category', 'like', '%'.$category.'%')

            ->orWhere('agents.location', 'like', '%'.$operation.'%')
            ->get();

In this query if the variable $category is empty no need to run that where condition. and $operation is null what where condition need to be skip. How to solve this issue ?

Upvotes: 0

Views: 573

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

try the following:

$users =  User::orderBy('id','asc')->join('agents', 'users.id', '=', 'agents.user_id')->select('users.id', 'users.first_name', 'users.last_name', 'users.email');
if(!is_null($category)) {
$users =  $users->where('agents.category', 'like', '%'.$category.'%')->orWhere('agents.location', 'like', '%'.$operation.'%');
}
$users = $users->get();

or:

$users =  User::orderBy('id','asc')->join('agents', 'users.id', '=', 'agents.user_id')->select('users.id', 'users.first_name', 'users.last_name', 'users.email')->where('agents.location', 'like', '%'.$operation.'%');
if(!is_null($category)) {
$users =  $users->orWhere('agents.category', 'like', '%'.$category.'%');
}
$users = $users->get();

Upvotes: 3

Related Questions