How to calculate the minimum value in Laravel collection?
Laravel

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.

Get The latest Coding solutions.

Subscribe to the Email Newsletter