A few other collection methods sum(), avg(), isEmpty(), isNotEmpty(), reverse(), shuffle(), take() and chunk()

1. sum() - It calculates total value of given field from collection array

$ratings = Rating::all();
$totalPoints = $ratings->sum('rating'); // suppose, rating is field in ratings table

2. avg() - It calculates average value of given field from collection array

$ratings = Rating::all();
$avgPoint = $ratings->avg('rating'); // suppose, rating is field in ratings table


3. isEmpty() - It checks and returns true if collection array is empty

$ratings->isEmpty()

4. isNotEmpty() - It checks and returns true if collection array is not empty

$ratings->isNotEmpty()


5. reverse() - It reverses the order of items in collection array

$posts = Post::all()->pluck('id');
$posts->reverse()

6. shuffle() - It randomizes the order of items in collection array

$posts = Post::all()->pluck('id');
$posts->shuffle()


7. take() - It takes given number of items from top of the collection array

$posts = Post::all()->take(3);


8. chunk() - It groups items in predefined size in separate collection array


$users = User::all();
$users->chunk(5) 

Related Posts


Using collection method reduce()