Collections - Collection Methods

It provides array manipulation methods with clean, fluent syntax. it is a fluent convenient wrapper for array of data
 

Using pluck() method of Laravel Collection

It helps to retrieve array for a given key.  $categories = Category::where('is_popular',1)->pluck('id'); Example above, fetches list of category ids only...


Using sortBy() collection method for sorting relation after eloquent query if required

Suppose there is a relation Post hasMany comments. By default laravel does sorting by desc for child relation. However, if...


Using collection method filter() and map() on eloquent queries instead of using loop and if statement

We are not using collection method where() for the sake of this example for using collection methods filter() and map()Suppose...


Using collection method map() in another way

map() method is used to iterate all collection items and helps to make changes to themSuppose, we need to change...


Using collection method reduce()

reduce() method is used to get single result from eloquent collectionSuppose, we need to do summation on each rating field...


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,...


Array manipulation with most commonly used Laravel collection methods

In PHP development, efficient array manipulation is a must in many applications. Laravel, one of the most popular PHP frameworks,...