Working with Collections in Laravel (Invoice example)

Collections have been around since the start in Laravel. In the early days they could be used on any Eloquent Model, but now they can be instantiated from almost any object/array data.

In this example, I'll show how they can be useful in an invoicing system.

Lets say we have the following POST data of the items to be added to the invoice. (demonstrated as an Array of Arrays)

array:3 [  
    0 => array:8 [
        "item" => "Line item 1: Dinosaurs"
        "quantity" => 10
        "per_unit" => 500499.12
    ],
    1 => array:3 [
        "item" => "Line item 2: Cages",
        "quantity" => 5,
        "per_unit" => 15499.99
    ],
    2 => array:3 [
        "item" => "Line item 3: Food for a week",
        "quantity" => 10,
        "per_unit" => 1000
    ]
]

We can then put this data into a collection:

$items = collect($_POST['items']);

// Lets calculate the price for each (quantity x per_unit)
$item = $items->map(function( $item ) {
    $item['price'] = $item['quantity'] * $item['per_unit'];
    return $item; 
})

// Maybe we want just the items with high quantities
$items = $items->where(function($item) {
    return $item->quantity >= 10;
});

// Maybe we want to keep all of the items where price is less than 1,000 (or remove those above)
$items = $items->filter(function( $item ) {
    return $item->price <= 1000;
})

// Lets sort by price, so they are shown the lowest priced items first
$items = $items->sortBy("price");

// Lets calculate the total invoice price
$invoice_total = $items->sum('price');

// How many invoice items are left?
$invoice_items = $items->count();

Again, the reason this is so useful is it can be done with any array/object data.

Further reading: