How To Use Conditional Clauses With Example Using Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.Now we discuss how can conditional clauses can be used in laravel.

How Conditional Clauses Used In Laravel With An Example

Conditional Clauses

Sometimes you may want clauses to apply to a query only when something else is true. For instance you may only want to apply a where statement if a given input value is present on the incoming request. You may accomplish this using the when method:
 

$role = $request->input('role');

$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();


The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.


You may pass another Closure as the third parameter to the when method. This Closure will execute if the first parameter evaluates as false. To illustrate how this feature may be used, we will use it to configure the default sorting of a query:
 

$sortBy = null;

$users = DB::table('users')
->when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();

Related Post