Albert Albert - 3 months ago 17
PHP Question

Laravel: find out if variable is collection

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?

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

}