Custom Collections in Laravel. Is there any suggestion for custom Collections in Laravel?
You can define a collection to any of your models. It’s a great way to organize your code and it also brings it closer to your domain.
<?php namespase APP\Collections\Transaction; class TransactionCollection extends Collection { public function weigthtedPricePerShare(): float { $sunOfProducts = $this->sum(function(Transaction $transaction) { return $transaction->quantity * $transaction->price_par_share }); if($this->sumQuantity() === 0.00) { return 0; } return $sunOfProducts / $this->sumQuantity(); } } ?>
First, you need to define your own collection class.
You can define some very useful methods that you need often when you work with a collection of a given model.
<?php namespase APP\Collections\Transaction; class TransactionCollection extends Collection { public function weigthtedPricePerShare(): float { $sunOfProducts = $this->sum(function(Transaction $transaction) { return $transaction->quantity * $transaction->price_par_share }); if($this->sumQuantity() === 0.00) { return 0; } return $sunOfProducts / $this->sumQuantity(); } } ?>
After that, you need to override the newCollection() method of the model.
It tells Laravel that any time you query more than one model it needs to return a TransactionCollection:
<?php namespase App\Models class Transation extends Model { use HasFactory; public function newCollection(array $model = []): TransactionCollection { return new TransactionCollection($model); } } ?>
Question and answer is powered by AnsPress.io