6 months ago

Type-hint custom Laravel Collection items on functions like ->first()

Posted 6 months ago by cannect

First off, let me tell you the endresult I want in my project. I want to be able to type for example the following in PHPStorm: $cartItems->first()->amount where amount is autocompleted because it is a CartItem with a property amount

Single CartItem

I have a Spatie Date Transfer Object (just a class really):

use Spatie\DataTransferObject\DataTransferObject;

class CartItem extends DataTransferObject
    public string $uuid;
    public string $name;
    public int $price;
    public string $amount;


CartItems Collection

I have a custom Collection like this:


use Illuminate\Support\Collection;

class CartItems extends Collection


Now when I create a CartItems collection I want to be able to do the following:

$cartItems = new CartItemsCollection([]);
$firstAmount = $cartItems->first()->amount // <--- amount is NOT autocompleted

And yes, I understand I can do:

$cartItems = new CartItemsCollection([]);
/** @var CartItem $cartItem */
$cartItem = $cartItems->first();
$firstAmount = $cartItem->amount // <--- amount is autocompleted

But my question is how to get the type hinting to work everywhere without doing that last example. It should be possible in PHP 7.4 I think, but I can't get it figured out.

What I tried

I have tried this so far in my CartItems collection class:

use Illuminate\Support\Collection;

class CartItems extends Collection

    /** @var CartItem[]  */
    protected $items = [];

     * Create a new collection.
     * @param  CartItem[]  $items
     * @return void
    public function __construct($items = [])
        return parent::__construct($items);

    public function current(): CartItem
        return $this->collection[ $this->position ];


Would be great if we can get this working!

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