How to calculate the minimum value in Laravel collection?
In Laravel any version like Laravel 5, Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10, you can use the min method to calculate the minimum value in a collection. The min method returns the minimum value of a given key or attribute in the collection. Here's an example:
$collection = collect([5, 3, 8, 1, 2]);
$minValue = $collection->min();
In this example, `$minValue` will be equal to `1`, which is the minimum value in the collection.
If you have a collection of objects and you want to find the minimum value based on a specific attribute or key, you can pass that key to the `min` method like this:
$collection = collect([
['name' => 'John', 'age' => 32],
['name' => 'Jane', 'age' => 28],
['name' => 'Bob', 'age' => 45],
]);
$minAge = $collection->min('age');
In this example, `$minAge` will be equal to `28`, which is the minimum age in the collection.
You can also use a callback function with the `min` method to calculate the minimum value based on a more complex condition. For example:
$collection = collect([5, 3, 8, 1, 2]);
$minValue = $collection->min(function ($value) {
return $value * 2;
});
In this example, `$minValue` will be equal to `2`, which is the minimum value of `$value` * 2 in the collection.
Hope, it will save your time.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
Callum Davies
PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.