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

来源:转载

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 Collectionsare a broader term, whereas Eloquent Collectionsare 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:

PHP

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

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

PHP

[ ['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],] [ ['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.

PHP

$average_price = $books->avg('price'); // in our case, 12.5 $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:

PHP

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

And the result:

PHP

[[ ['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],]] [[['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:

PHP

$books->contains('title', 'The One Thing'); // TRUE$books->contains('title', 'The Second Thing'); // FALSE $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.

PHP

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

Result:

PHP

[ ['title' => 'Lean Startup', 'price' => 10], ['title' => 'Laravel: Code Bright', 'price' => 20],] [ ['title'=>'Lean Startup','price'=>10], ['title'=>'Laravel: Code Bright','price'=>20],]

5. filter()

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

PHP

$expensive_books = $books->filter(function ($book) { return $book->price > 10;}); $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.

PHP

$books->forget('price'); $books->forget('price');

Result:

PHP

[ ['title' => 'Lean Startup'], ['title' => 'The One Thing'], ['title' => 'Laravel: Code Bright'], ['title' => 'The 4-Hour Work Week'],] [ ['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:

PHP

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

Result:

PHP

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

8. keyBy()

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

PHP

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

Result:

PHP

[ '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],] [ '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().

PHP

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

Result:

PHP

[ ['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],] [ ['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.

PHP

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

Result:

PHP

[10, 15, 20, 5] [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 Collectionsand Basic Collections.

Keep digging deeper into Laravel world!

Facebook Twitter Google+ LinkedIn



分享给朋友:
您可能感兴趣的文章:
随机阅读: