Laravel 9 - Usage of Laravel Eloquent when() conditions

Published on Aug 15, 2022

Hello Artisans, today I'll show you how to use Laravel one of handy eloquent method called when(). It is quite useful when we want to querying somethin based on our requested data. Or when we want to querying something conditionally. It'll work out of the box to minimize our work and our querying performance. So let' look how we can use in our Laravel Application.

Using if Condition

So, if we've to check if a requested data exists or not we use a if(condition), and so on we also do that in our query like the below code.

public function queryWithoutWhen(Request $request)
    {
        if ($request->status == 1)
        {
            $users = User::where('status',1)->get();
        }
        else{
            $users = User::all();
        }

    }

But it's a very bad pattern/style for writing the query and we should avoid that one. Instead we should use Laravel's Eloquent method called when().

Using when()

Laravel provide use a handy method called when(), which is used for a conditional based querying. Means the query is to run when a given condition is true. Let's look at the below condition.

public function queryWithWhen(Request $request)
    {
        $users = User::when($request->status == 'active',function ($query){
            $query->where('status','active');
        })->get();
    }

So what does in above condition. Here we'll perform a query where if a user request to see only active user then where() condition will run. But if user doesn't request anything then he'll see all the list of users. And ideally it is the simplest and standard way to write the query.

And not only that, if we want to use multiple condition on that query, we can use also multiple when() condition in our query. Like the below code.

public function queryWithMultipleWhen(Request $request)
    {
        $users = User::when($request->status == 1,function ($query){
            $query->where('status',1);
        })->when($request->user_type == 1,function ($query){
            $query->where('user_type',1);
        })->get();
    }

That's it for today. If you've any question, catch me in the comment section. Hope you'll enjoy through this tutorial. Thanks for reading :)

Comments (0)