Laravel: find out if variable is collection

function is_collection($param): bool
{
    return (bool) (($param instanceof \Illuminate\Support\Collection) || ($param instanceof \Illuminate\Database\Eloquent\Collection));
}

If you are using it a lot you might just want to make function for it.

Combination of @Konchog & @Jonathan Ma answer.


You can try something like this

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) {
    ....do whatever for a collection....
}

The class being used is incorrect here. In a general sense, you should be testing for the base class.

use Illuminate\Support\Collection;

....
if($images instanceof Collection) { 
 ....
}

The answer by @Konchong points this out, but I want to make a difference explicit for others.

There is a difference between Illuminate\Support\Collection, the base class used by many types of collections in Laravel, and Illuminate\Database\Eloquent\Collection, which extends the base class but has additional functionality and within its code, aliases the base class as BaseCollection. This is what you get when you execute a query builder, through a model class and a function like get(). An ordinary collection is made with collect(["my", "array"]) instead.

Note that both classes results in a different set of methods. For example, load, loadMissingRelation, and a number of other methods are present in the subclass that are not present in the parent class. Inside of the methods in the database subclass however, are a number of escape-hatch if statements that ensure that if someone accidentally uses the subclass when they mean the base class in an unintended fashion (such as adding an element to the collection), the collection will not break.

Note that the following is true:

User::get() instanceof \Illuminate\Database\Eloquent\Collection;
User::get() instanceof \Illuminate\Support\Collection;
collect(["hello", "i", "am", "a", "base", "collection"]) instanceof \Illuminate\Support\Collection;

Note that the following is false:

collect(["hello im a", "base collection"]) instanceof \Illuminate\Database\Eloquent\Collection;
is_array(collect(["hello im a", "base collection"]));

Be mindful that while a collection is essentially a wrapper around an array and with very powerful methods, it is not an array and can often fail or throw exceptions in the standard php array functions.