Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
May 19, 2023
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(); if($role==’user’) { $query->where(‘role’, ‘user’); } else { $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); })->get();
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’); })->get();
More info: https://laravel.com/docs/master/queries#conditional-clauses