I am trying to find the best way to retrieve the Eloquent Model type of items in a collection.
Of course I can get the first item and ask for its type, but it's likely that I hit an empty collection and there's no other way to get the type then. This question is similar to this one here C# - Get the item type for a generic list but I couldn't find any addressing this for laravel or php.
There is a function on the Collection called getQueueableClass() that will return the type of the items in the collection. The function basically does a get_class($collection->first()) but it takes care of asking if the collection is empty before. But, as you can see in the source code if there are objects with different types on the collection it will throw an exception.
https://github.com/illuminate/database/blob/master/Eloquent/Collection.php#L392
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With