📜  laravel collection max - PHP (1)

📅  最后修改于: 2023-12-03 15:32:33.032000             🧑  作者: Mango

Laravel Collection Max - PHP

Introduction

Laravel Collection Max is a built-in method provided by Laravel to retrieve the maximum value of a given key from a collection. This method allows you to work with collections in a more efficient and concise way, in comparison to writing custom logic to retrieve the maximum value.

Syntax

max($key = null)

  • $key (optional): The key for which the maximum value should be retrieved. If no key is given, then the maximum value of the entire collection is retrieved.
Example

The following example demonstrates how to use the max() method to retrieve the maximum 'age' value from a collection of users:

use Illuminate\Support\Collection;

$users = new Collection([
    ['name' => 'Alice', 'age' => 23],
    ['name' => 'Bob', 'age' => 29],
    ['name' => 'Charlie', 'age' => 21],
]);

$maxAge = $users->max('age');

echo $maxAge; // 29
Explanation

In the example above, we first create a new collection containing three users, each with a 'name' and 'age' property.

Next, we call the max() method on the collection, passing in the 'age' key. This returns the maximum value of the 'age' property in the collection, which is 29.

Finally, we output the maximum age value to the screen using echo.

Conclusion

In short, the Laravel Collection Max method is a powerful tool that can be used to quickly and easily retrieve maximum values from a collection. Whether you're working with user data or any other type of collection, this method can help you write cleaner and more readable code.