Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get item type of an Eloquent collection in Laravel

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.

like image 692
mahmoud fathy Avatar asked Dec 19 '25 04:12

mahmoud fathy


1 Answers

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

like image 161
Esteban Garcia Avatar answered Dec 21 '25 20:12

Esteban Garcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!