PASSWORD RESET

Your destination for complete Tech news

How to calculate the minimum value in Laravel collection?

1.44K 0
< 1 min read

To calculate the minimum value in a Laravel collection, you can use the min method. This method will return the minimum value of the items in the collection.

Here’s an example:

$collection = collect([1, 2, 3, 4, 5]);
$min = $collection->min();

// $min is now 1

You can also pass a callback to the min method to specify a custom comparison function:

$collection = collect([1, 2, 3, 4, 5]);
$min = $collection->min(function ($value) {
    return $value * -1;
});

// $min is now 5

If you want to calculate the minimum value of a specific key of the items in the collection, you can use the pluck method to extract the values before calling the min method:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$min = $collection->pluck('age')->min();

// $min is now 25

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.