I want to find out if a variable is a collection.
I can't use is_object() because it will be true even if it is not an collection. For now I use this, and it works:
if(is_object($images) && get_class($images) != 'Illuminate\Database\Eloquent\Collection') {
But I think it's so ugly that I spend time asking you about another solution.
Do you have any idea?
You can use the contains() method in Laravel for Check some specific key of value exists or not. If value available in the collection for the specific key then returns true.
Laravel collection is a useful feature of the Laravel framework. A collection works like a PHP array, but it is more convenient. The collection class is located in the Illuminate\Support\Collection location. A collection allows you to create a chain of methods to map or reduce arrays.
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.
The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.
Couldn't you use
if(is_a($images, 'Illuminate\Database\Eloquent\Collection')) { ....do whatever for a collection.... } else { ....do whatever for not a collection.... }
Or
if ($images instanceof \Illuminate\Database\Eloquent\Collection) { }
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