3 months ago

Laravel Illuminate\Support\Collection - FirstOrNew (and similar) possible with extending? (Not Eloquent)

Posted 3 months ago by booni3

I am using Laravels collection for creating entities within a DDD type (very loose!) environment. It works well but I really miss the helper functions that you can make use of with Eloquent and was wondering if there is a way to get this similar functionality extended into the Collection function.

For example, I am doing something similar this a lot:

final class InventoryAggregateRoot extends AggregateRoot
    /** @var Collection | LocationItem[] */
    private $inventoryItems;

    public function __construct()
        $this->inventoryItems = new Collection();

    public function firstOrCreateInventoryItem($id)
        $inventoryItem = $this->inventoryItems->firstWhere('id', $id);

        if(! $inventoryItem){
            $inventoryItem = new InventoryItem($id);

        return $inventoryItem;

but would love to do something like this:

$inventoryItem = $this->inventoryItems->firstOrCreate('id', $id);

It seems like this could be quite easily added in... but I feel like I may be missing something. Why is this kind of functionality not in Laravel already?

Please sign in or create an account to participate in this conversation.