Laravel Database Conditional Clauses – The Laravel Database Conditional Clauses is used to apply a query only when something else is true.
Laravel Database Conditional Clauses.
Let us understand how to use Laravel Database Conditional Clauses.
Function:-
There are some followings function available in Laravel Database Conditional Clauses.
Conditional Clauses
Sometimes you want clauses to apply a query only when something else is true. Like, you can only want to apply where statement if a given input value is present on the incoming request.
Let’s look at a simple example.
$role = $request->input('role'); $users = DB::table('users') ->when($role, function ($query) use ($role) { return $query->where('role_id', $role); }) ->get(); |
The when method is only execute when the first parameter is true. If the first parameter is false, the Closure will not be executed.
Let’s look at a simple example.
$sortBy = null; $users = DB::table('users') ->when($sortBy, function ($query) use ($sortBy) { return $query->orderBy($sortBy); }, function ($query) { return $query->orderBy('name'); }) ->get(); |