Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

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

Premium
1:44

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 Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

PC
Pavel Chebukin ✓ Link copied!

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!