Courses

Laravel 12 Eloquent: Expert Level

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

Summary of this lesson:
- Using when() for conditional queries
- Implementing dynamic query conditions
- Replacing if-else statements with when()
- Understanding conditional clause benefits

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.

use Illuminate\Database\Eloquent\Builder;
 
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.


Code for this lesson can be found on GitHub.

Previous: Local and Global Scopes for Repeating Conditions
avatar

This is an interesting feature "when" but almost the same amount of code, so I'm not sure is it better to use "when" more than native PHP "if". More framework dependency and a little bit more difficult for people who only learn Laravel. Not a big advantage. But will know now. Thanks!

avatar
You can use Markdown
avatar
You can use Markdown