Source: martinjoo.dev

Blog for Laravel Artisans
They have a really functional, Javascript-y taste: $sum = collect($numbers) ->filter(fn (int $x) => $x > 10) ->map(fn (int $x) => $x * 2) ->sum(); Another remarkable aspect of Laravel is custom collections. Let’s say we’re working on an investment portfolio application where we have transactions and holdings.

Fortunately, in Laravel, we can write a custom collection for a model: namespace App\Collections; use App\Models\Transaction; use Illuminate\Database\Eloquent\Collection; class TransactionCollection extends Collection { public function weightedPricePerShare(): float { if ($this->sum('quantity') === 0.00) { return 0; } $sumOfProducts = $this ->sum(fn (Transaction $transaction) => $transaction->quantity * $transaction->price_per_share ); return $sumOfProducts / $this->sum('quantity'); }}

The last step is to instruct Laravel to actually use this class whenever we're creating a new collection from Transaction models: namespace App\Models; use App\Collections\Transaction\TransactionCollection; use Illuminate\Database\Eloquent\Factories\HasFactory; class Transaction extends Model { use HasFactory; public function newCollection(array $models = []): TransactionCollection { return new TransactionCollection($models); }}

When the context of your function is a lot of model it’s a good indicator of a custom collection.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners