Posted 2021-07-20 with tags Laravel collections, PHP, Laravel models, Eloquent

Illuminate\Support\Collection is the base class used by many types of collections in Laravel, whereas Illuminate\Database\Eloquent\Collection is used by Laravel models. It extends the base class with additional functionality, and aliases the base Collection class as BaseCollection, and is returned when executing common Laravel query builder requests, or requests through a model class function such as get(). A regular collection is instantiated via collect(["foo", "bar"]).

Both classes result in a slightly different set of methods; for example, load, loadMissingRelation, and other methods are present in the subclass but not in the parent class. However within th subclass there are weird "escape-hatch" statements that attempt to ensure compatibility between the two collection instances, but instead cause confusion instead of immediately returning an error. Check into the differnces between the count(), and first() method betwen the two implementations in order to investigate the differences.

Determine if Collection or Eloquent Model

Use instanceof to verify whether a given variable is a collection or an Eloquent model:


// Check if collection
if ($variable instanceof \Illuminate\Support\Collection) {

Eloquent Model

// Check if Eloquent model
if ($variable instanceof \Illuminate\Database\Eloquent\Model) {