10 less-known (but awesome!) Laravel Collections methods

Laravel Eloquent is awesome – probably I don’t need to tell you that. What is less known is the list of methods to work with Eloquent Collections. You can filter them, slice them, easily modify etc. But let’s look at it one by one.

A little notice here – that Collections are a broader term, whereas Eloquent Collections are the implementation of these broader Collections. So everything that we cover here in this article can be used for both instances.

So, for example, you have Laravel code like this:

$books = Book::where('release_year', 2015)->get();

In this case $books is a collection, which is basically an array with additional features. For example it can look like this:

[
    ['title' => 'Lean Startup', 'price' => 10],
    ['title' => 'The One Thing', 'price' => 15],
    ['title' => 'Laravel: Code Bright', 'price' => 20],
    ['title' => 'The 4-Hour Work Week', 'price' => 5],
]

So what can we do with it? Important note: all those functions below are called without querying the database – so you run a query once and then perform all actions with collection “offline”.

1. avg()

If you want to calculate average price of the book, you don’t need to query database separately for that.

$average_price = $books->avg('price'); // in our case, 12.5

2. chunk()

If you want to split the results by equal parts, for example to view them as columns, it can look like this:

$chunks = $books->chunk(2);
$chunks->toArray();

And the result:

[
[
    ['title' => 'Lean Startup', 'price' => 10],
    ['title' => 'The One Thing', 'price' => 15]
],
[
    ['title' => 'Laravel: Code Bright', 'price' => 20],
    ['title' => 'The 4-Hour Work Week', 'price' => 5],
]
]

3. contains()

Simple – check whether our collection contains a certain value in one of the fields:

$books->contains('title', 'The One Thing'); // TRUE
$books->contains('title', 'The Second Thing'); // FALSE

4. every()

Another method of splitting the collection into a different columns. This time – every() would form a new collection, consisting of every N-th element.

$books->every(2); // every 2nd element

Result:

[
    ['title' => 'Lean Startup', 'price' => 10],
    ['title' => 'Laravel: Code Bright', 'price' => 20],
]
Have you tried our tool to generate Laravel adminpanel without a line of code?
Go to QuickAdminPanel.com

5. filter()

This method was already a topic of separate mini-article so will just briefly repeat:

$expensive_books = $books->filter(function ($book) {
    return $book->price > 10;
});

6. forget()

This is a method to use if you want to get rid of one of the columns.

$books->forget('price');

Result:

[
    ['title' => 'Lean Startup'],
    ['title' => 'The One Thing'],
    ['title' => 'Laravel: Code Bright'],
    ['title' => 'The 4-Hour Work Week'],
]

7. implode()

Really similar to a well-known PHP array implode() function. The result is a joined string:

$books->implode('title', ', ');

Result:

'Lean Startup, The One Thing, Laravel: Code Bright, The 4-Hour Work Week'

8. keyBy()

This is a really useful one to use with foreach loops later. Basically, it transforms a collection into an array with your chosen key.

$by_key = $books->keyBy('title');
$by_key->all();

Result:

[
    'Lean Startup' => ['title' => 'Lean Startup', 'price' => 10],
    'The One Thing' => ['title' => 'The One Thing', 'price' => 15],
    'Laravel: Code Bright' => ['title' => 'Laravel: Code Bright', 'price' => 20],
    'The 4-Hour Work Week' => ['title' => 'The 4-Hour Work Week', 'price' => 5],
]

9. map()

If you want to extract some values and perform some actions with them – there’s not only foreach().

$discounted_books = $books->map(function ($item) {
    return ['title' => $item->title, 'price' => $item->price / 2];
});

Result:

[
    ['title' => 'Lean Startup', 'price' => 5],
    ['title' => 'The One Thing', 'price' => 7.5],
    ['title' => 'Laravel: Code Bright', 'price' => 10],
    ['title' => 'The 4-Hour Work Week', 'price' => 2.5],
]

10. pluck()

This method allows you to extract just one column easily.

$prices = $books->pluck('price');
$plucked->all();

Result:

[10, 15, 20, 5]

So this is hand-picked 10 less-known methods, but it’s not even a half of what’s available. You can find full list with short examples in the official documentation for Eloquent Collections and Basic Collections.

Keep digging deeper into Laravel world!

Like our articles?
Check out our Laravel online courses!

16 COMMENTS

  1. My favourite method at the moment is groupBy(‘key’). Super useful for grouping a list of events by date.

  2. Thanks for this. Just wanted to add that you can use pluck() to extract two columns which is super useful for creating select boxes.

    $book_list = $books->pluck(‘title’, ‘id’);

    $book_list is now a collection that looks like:
    [
    1 => ”Lean Startup’],
    2 => [‘The One Thing’],
    3 => [‘Laravel: Code Bright’],
    4 => [‘The 4-Hour Work Week’],
    ]

    Which you can then use in a blade template via the Illuminate\Html\FormBuilder select() method like:

    Form::select(‘book_id’, $book_list, old(‘book_id’, $default_book_id), [‘class’ => ‘form-control’]);

  3. Hello.How do I check If my entered number falls in which row.
    for eg:I entered 9
    and I have a table where a column named price is as below

    id price
    1 5
    2 10
    3 15

    If I entered 9,I want to get id 1 ,as my entered price is below 10,but above 5.Can you please help me

  4. Here is one you may have left out. Dot notation when searching for nested properties

    collect([[‘name’ => [‘first’ => ‘Peter’]], [‘name’ => [‘first’ => ‘Joe’]]])->where(‘name.first’, ‘Joe’)

LEAVE A REPLY

Please enter your comment!
Please enter your name here