💡How to use when() in Laravel
In development with Laravel, having clean and readable code is just as essential as having functional code. One of the less-touted gems that makes your code look more beautiful is the when() method — provided both in Eloquent queries and Collections.
This blog will guide you through the usage of when() in Laravel with real-life examples, and discuss why and when to use it. While writing generic queries or search queries with different parameters, we usually use if else statements but we will replace these if else statements with when() to make our code more readable and maintainable.
🧠 What is when() in Laravel?
when() is a method that is utilized to conditionally execute logic — without writing dirty if statements. It exists in:
- Query Builder
- Eloquent
- Collections
Example :
Usually for search queries, we write search queries like as below
$query = Post::query(); if ($request->status) { $query->where('status', $request->status); } if ($request->category_id) { $query->where('category_id', $request->category_id); } $posts = $query->get();
But with when(), we can make it more simple and maintainable.
$status = $request->status; $categoryId = $request->category_id; $posts = Post::query() ->when($request->status, function ($query, $status) { $query->where('status', $status); }) ->when($request->category_id, function ($query, $categoryId) { $query->where('category_id', $categoryId); }) ->get();
You can use the same syntax with Collections as well as Query Builders.
🎯 When Should You Use when()?
Use when() whenever:
- You have optional filters or parameters in queries
- You're working with Collections that require conditional logic
- You don't want to use multiple if statements
- You want to conditionally make logic within pipelines dynamic
✅ Summary
Laravel's when() method is an elegant yet efficient means to express condition-based logic in a concise and readable form. It minimizes clutter, makes code more readable, and adheres to Laravel's philosophy of clean coding.
📌 Key Points:
- Available in Query Builder, Collections, and Pipelines
- Takes a condition, a callback (and an optional fallback)
- Improves readability and maintainability