3

If I do this:

$obj = factory(Object::class)->make();

collect($obj);

I am returned a collection of type:

Illuminate\Support\Collection

Laravel also lets you define your own collections with their specific methods. In the model, you do:

public function newCollection(array $models = [])
{
    return new CustomCollection($models);
}

and you would make your CustomCollection, starting like this, in the file CustomCollection.php:

class CustomCollection extends Collection
{

I'm wondering how I can return a collection of type:

Illuminate\Database\Eloquent\Collection

or, in the case of creating my own custom collection, how could I return a collection of type:

App\Models\CustomCollection

I'd like to do this with the collect() helper or any other way where I don't access the database for purposes of writing PHPUnit tests.

==========

EDIT: I'm using factory(Object::class)->make() to spoof Eloquent objects which I was trying to roll into collections.

If you just do factory(Object::class, 1)->make() instead, the factory rolls the single instance of Object::class into an Eloquent collection for you.

shaedrich
  • 5,457
  • 3
  • 26
  • 42
iateadonut
  • 1,951
  • 21
  • 32

2 Answers2

5

The collect() helper just creates a new instance of Illuminate\Support\Collection.

function collect($value = null)
{
    return new Collection($value);
}

You can do the same with any collection.

Illuminate\Database\Eloquent\Collection

$collection = new Illuminate\Database\Eloquent\Collection($value);

App\Models\CustomCollection

$collection = new \App\Models\CustomCollection($value);
Remul
  • 7,874
  • 1
  • 13
  • 30
1

Since you are using:

$obj = factory(Object::class)->make();

to spoof Eloquent objects, if you just do this instead:

$collection = factory(Object::class, 1)->make()

The factory() rolls the single instance of Object::class into an Eloquent collection for you. The 1 is the number of objects in the collection produced, so you can change that to a 2 if you want 2 objects, etc.

shaedrich
  • 5,457
  • 3
  • 26
  • 42
iateadonut
  • 1,951
  • 21
  • 32