Laravel Usage of Laravel Eloquent when() Conditions

Hello artisans, today I'll show you how to use Laravel one of the handy eloquent methods called when(). It is quite useful when we want to query something based on our requested data. Or when we want to query something conditionally. It'll work out of the box to minimize our work and our querying performance. So let's look at how we can use it 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 questions, catch me in the comment section. Hope you've enjoyed this tutorial. Thanks for reading.