Many cases we need to write conditional queries with laravel eloquent. For that we generally use “if” and “else” conditions and based on the condition we are used to make our query. Now laravel supports these types of conditional queries using the when() method.


Laravel provides a when() method to apply those kinds of conditional queries. Here we can understand by using the example.


For example we are used to make conditional queries like below:

$role = $request->role;
$query = Users::query();

    $query->where(‘role’, ‘user’);
    $query->where(‘role’, ‘admin’);

$users =$query->get();

Now we can simplify this by using when() method provided by laravel

$users = Users::when($role, function (Builder $query, string $role) {
      $query->where('role', $role);

In addition to this we can also pass value to the when method that needs to be checked.

$query = User::query();

$query->when(request('role', false), function ($q, $role) {
    return $q->where('role', $role);
$users = $query->get();

We can also pass the callback/clousar function as default value which needs to be executed only if the condition matched. We can pass greater than or less then conditions as well.

$users = User::when(request('filter') == 'counts’, function ($q) {
    return $q->where('counts’, '>', request('likes_count', 0));
}, function ($q) {
    return $q->orderBy('created_at', ‘DESC’);

More info:

Support On Demand!