How to use eloquent when - more elegant way of using if statement

If dynamic query is being built using eloquent builder based on dynamic search queries such as user id or post title, we can use when instead of if statement.

First let us see how it will look like with if statement

//In Controller

$query = Post::query();

if(request('user_id')) {
    $query->where('user_id', request('user_id'));
}

if(request('post_title')) {
    $query->where('title', request('post_title'));
}

$posts = $query->get();

Now if we use when() method for the example above the snippet will look like below.

//In Controller

$posts = Post::select([ 'id', 'user_id' ,'title', 'created_at','updated_at'])->when( request('user_id'), function($query) {
    return $query->where('user_id', request('user_id'));
})->when( request('post_title'), function($query) {
    return $query->where('title', 'like' , '%'.request('post_title').'%');
})->get();

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent