Laravel Type Hint Eloquent Collection

Well this may be trivial. But I am stuck.

I need to pass an argument to a function but need to type hint it like so:

    private function printUsers(Collection<User> users) {
     foreach($users as $user) {
       print($user->fullName)
     }
    }

How do I type hint this collection, because I want a collection of a specific model?


Solution 1:

Generics are not supported in PHP. However if you are using certain IDEs (at least PhpStorm does this) you can put the generic in the docblock:

   /**
    * @param Collection<User> $users
    */
   private function printUsers(Collection $users) {
     foreach($users as $user) {
       print($user->fullName)
     }
    }

However this will still not work because Laravel has not type-hinted the collection as generic (not yet at least, this is coming in Laravel 9).

The general way to resolve this (again using a docblock) is to do the "hacky" typehint of:

   /**
    * @param Collection|User[] $users
    */
   private function printUsers(Collection $users) {
     foreach($users as $user) {
       print($user->fullName)
     }
    }

This will typehint $users as an array accessible variable with User members, which is probably close enough for your needs but:

(a) completion only works in IDEs that support the User[] syntax

(b) It only works when iterating i.e. it's not a true generic