Ad

Laravel: Find Out If Variable Is Collection

- 1 answer

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?

Ad

Answer

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) {

}
Ad
source: stackoverflow.com
Ad