Matt Larsuma
Matt Larsuma

Reputation: 1519

Laravel 5.4 - instanceof Collection not returning true when being passed what seems to be a Collection

I'm working with a method that does an instanceof Collection check:

if ($group instanceof Collection) {
    $group = $group->pluck('name');
}

This is being used in many places, so I am not able to change it (not that I want to), but I do want to pass in a collection of group names. I'm instantiating my collection like so:

$group = collect(['one', 'two', 'three']);

When I dd the $group variable it looks a duck,

Collection {#612
  #items: array:3 [
    0 => "one"
    1 => "two"
    2 => "three"
  ]
}

but returns false in that instanceof check. Any ideas why this might be so?

Upvotes: 2

Views: 1458

Answers (2)

Jonathon
Jonathon

Reputation: 16283

Your issue is that the instanceof is checking for an instance of Eloquent's extension of Collection.

use Illuminate\Database\Eloquent\Collection;

If you change your use the base collection class, it should work:

use Illuminate\Support\Collection;

Upvotes: 3

Tim Lewis
Tim Lewis

Reputation: 29258

There are (at least) two different types of Collection classes in Laravel:

  • Illuminate\Support\Collection
  • Illuminate\Database\Eloquent\Collection

Check this code:

$collection = collect([1, 2, 3]);
dd(
  $collection instanceof Collection,
  $collection instanceof Illuminate\Support\Collection,
  $collection instanceof Illuminate\Database\Eloquent\Collection
);

In this case, the return I get is

false // Collection
true  // Illuminate\Support\Collection
false // Illuminate\Database\Eloquent\Collection

So, using collect() creates an instance of Illuminate\Support\Collection, but the version of Collect that's available (or included with a use statement) is not the correct one.

Upvotes: 2

Related Questions