Back to Course |
Laravel 11 Eloquent: Expert Level

Instead of Multiple If-Else, Use Eloquent When()

In Eloquent, there's an elegant syntax on how to write conditional queries. when the conditions depend, for example, on the request. Then you want to add where() statements dynamically.


In this example, we can have parameters user_id and is_completed from the GET request. The where() statement is added if either of these two parameters is present.

use App\Models\Task;
use Illuminate\Http\Request;
 
class HomeController extends Controller
{
public function index(Request $request)
{
$query = Task::query();
 
if ($request->has('user_id')) {
$query->where('user_id', $request->integer('user_id'));
}
 
if ($request->has('completed')) {
$query->where('is_completed', $request->boolean('completed'));
}
 
$tasks = $query->get();
 
foreach ($tasks as $task) {
dump($task->id . ': ' . $task->description);
}
}
}

Now, instead of making an if statement, we can use the when method on the Eloquent query. The first parameter must be the condition, and the second parameter is the closure with the query.

class HomeController extends Controller
{
public function index(Request $request)
{
$tasks = Task::query()
->when($request->integer('user_id'), function (Builder $query) use ($request) {
$query->where('user_id', $request->integer('user_id'));
})
->when($request->boolean('completed'), function (Builder $query) use ($request) {
$query->where('is_completed', $request->boolean('completed'));
})->get();
 
if ($request->has('user_id')) {
$query->where('user_id', $request->integer('user_id'));
}
 
if ($request->has('completed')) {
$query->where('is_completed', $request->boolean('completed'));
}
 
$tasks = $query->get();
 
foreach ($tasks as $task) {
dump($task->id . ': ' . $task->description);
}
}
}

Let's test it. In the database, I have 12 task records.

In the browser, if I add the query parameter ?user_id=2, I can see all tasks that belong to the user with an ID of two.

Additionally, if I add completed=true, I can see only tasks the user with the ID of two has completed.

You may still prefer the if statement, but I wanted to show you the Eloquent syntax of writing conditional queries.