Use When Instead of If in Laravel Collection for Elegant-Readable Code

Mohasin Hossain
2 min readJan 12, 2024

--

In Laravel, collections provide a powerful way to work with arrays of data, offering a wide range of methods to manipulate and filter the data. When working with collections, developers often find themselves using conditional statements like “if” to perform certain operations based on specific conditions. However, Laravel provides an elegant alternative in the form of the “when” method, which can lead to more concise and readable code.

Let’s see an example on it.

// Assume we have a collection of users
$users = collect([
['name' => 'John Doe', 'active' => true],
['name' => 'Jane Doe', 'active' => false],
['name' => 'Bob Smith', 'active' => true],
// ... more user data
]);

// Define a boolean variable to control the transformation
$shouldTransform = true;

// Using "if" condition to filter out inactive users and capitalize names
$filteredUsersWithIf = $users->map(function ($user) use ($shouldTransform) {
if ($shouldTransform) {
$user['name'] = strtoupper($user['name']);
return $user;
}
return null;
})->filter();

// Using "when" method with the boolean variable
$filteredUsersWithWhen = $users->when($shouldTransform, function ($collection) {
return $collection->map(function ($user) {
$user['name'] = strtoupper($user['name']);
return $user;
});
});

// Displaying results
echo "Filtered Users with If:\n";
print_r($filteredUsersWithIf->toArray());

echo "\nFiltered Users with When:\n";
print_r($filteredUsersWithWhen->toArray());

FYI (For Your Information) this is very basic example but you can found some situation to implement this nice when method for more readability and elegant code.

Hoping you found this helpful!

--

--

Mohasin Hossain
Mohasin Hossain

Written by Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux

Responses (1)