PHP

Using Eloquent Conditional Clauses with when()

Discover how to write cleaner Laravel Eloquent queries by conditionally applying clauses using the built-in when method.

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

$users = User::query()
    ->when($role, function ($query, $role) {
        return $query->where('role_id', $role);
    })
    ->paginate(15);
How it works: The 'when' method executes the given callback only when the first argument evaluates to true. This eliminates the need for messy if-else blocks when building conditional database queries based on incoming request parameters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs