Simplify Your Laravel Queries with the when() Method

Mohd Suhail
2 min readJul 26, 2023

Introduction: As a Laravel developer, you often encounter situations where you need to build dynamic queries based on various conditions. The when() method in Laravel's query builder provides an elegant and efficient way to handle such scenarios. In this article, we will explore the power of the when() method and demonstrate its usefulness with practical examples.

What is the when() Method?

The when() method is a powerful feature in Laravel's query builder that allows you to conditionally add clauses to your query based on runtime conditions. It takes two arguments: the first one being the condition to evaluate, and the second one being a closure where you can define the query clauses that should be applied when the condition is met.

Example 1: Filtering Products Based on User Input Let’s say you have an online store application, and users can search for products based on different filters, such as category, price range, and availability. Using the when() method, you can dynamically apply these filters to your query:

$categoryId = $request->input('category_id');
$minPrice = $request->input('min_price');
$maxPrice = $request->input('max_price');
$availability = $request->input('availability');

$products = Product::query()
->when($categoryId, function ($query, $categoryId) {
return $query->where('category_id', $categoryId);
})
->when($minPrice && $maxPrice, function ($query) use ($minPrice, $maxPrice) {
return $query->whereBetween('price', [$minPrice, $maxPrice]);
})
->when($availability, function ($query, $availability) {
return $query->where('availability', $availability);
})
->get();

Example 2: Filtering Posts by Tag in a Blog Application Consider a blog application with posts and tags. Users can search for posts by a specific tag. The when() method simplifies the filtering process based on user input:

$tagId = $request->input('tag_id');

$posts = Post::query()
->when($tagId, function ($query, $tagId) {
return $query->whereHas('tags', function ($query) use ($tagId) {
$query->where('id', $tagId);
});
})
->get();

Example 3: Prioritizing Query Conditions In some cases, you may need to prioritize query conditions based on user preferences. Here’s an example where we give priority to the “featured” flag in the database:

$isFeatured = $request->input('is_featured');
$category = $request->input('category');

$products = Product::query()
->when($isFeatured, function ($query) {
return $query->where('is_featured', true);
})
->when($category, function ($query, $category) {
return $query->where('category', $category);
})
->get();

Conclusion: The when() method in Laravel's query builder is a powerful tool that simplifies building dynamic queries based on runtime conditions. By leveraging the when() method, you can enhance the flexibility and readability of your code, making it easier to handle complex queries. Whether you're filtering search results, leveraging Eloquent relationships, or prioritizing query conditions, the when() method proves to be an invaluable asset in your Laravel development journey. So go ahead, and give it a try in your next project to see the magic it brings to your queries!

--

--

Mohd Suhail

I'm a Full-stack developer with a passion for software architecture and programming best practices. I love writing clean code, talking and writing about it .