Laravel Collections Make PHP Development Awesome
Laravel provides a lot of amazing tools out-of-the-box and collections are one of them. The collection class within Illuminate\Support is basically a wrapper that allows you to work with and manipulate arrays of data.
One of the things I’ve noticed that the class uses PHP’s default array methods such as, array_sum, array_map, array_keys, etc. within the map method, you can see that it utilizes array_map and array_keys:
/**
* Run a map over each of the items.
*
* @param callable $callback
* @return static
*/
public function map(callable $callback)
{
$keys = array_keys($this->items);
$items = array_map($callback, $this->items, $keys);
return new static(array_combine($keys, $items));
}
You can check out this within Laravel’s codebase on github! It’s always good to read code. It’s what makes you a better developer!
My Use Of Collections
Last night, I was playing around with some code and I wanted to get the total sum of expenses for a given project. I have a one-to-many relationship with the project model and the expense model. A project has many expenses. I do have a budget field to on the project table but that might be irrelevant for this example.
$amount = collect($expenses)->map(function($expense) {
return $expense->expense_amount;
})->sum();
$total_expenses = $amount->all();
In the example above, I use the collect helper to grab my expenses and the map method to iterate through the collection. Then, I get the sum of the $amount by passing/chaining sum() at the end of the collection. Finally, I store all items in the collection in a $total_expenses variable. Now, I can pass to $total_expenses variable into my view if I’d prefer.
Eloquent Models Return Collections By Default
When you return a an Eloquent model (let’s say Project::all() for example), it returns a collection by default instead of an array. Here’s an example of what Project::all() returns when you die and dump the data.
Talks On This Subject
I found a couple videos on this subject that can explain what collections are better than what I can. Here are those videos.
Skater Dev’s Video on Laravel Collections
Adam Wathan’s Laracon Talk
Closing Thoughts
In upcoming posts, I want to go more in depth into Laravel collections. Perhaps I can go over each collection method and provide an example on what it does. I would also like to talk about functional programming concepts as it interests me. Collections are an awesome tool and I plan on using them in my current Laravel projects. Anyway, stay tuned for tomorrow’s post!
Cheers.