2
2
2vtlk2016-11-16 06:32:12
Laravel
2vtlk, 2016-11-16 06:32:12

Is eager loading not compatible with custom collections in laravel?

If the model is eager loaded

public function companies()
{  
    $this->load('contacts.companies')
    // ...
}

and at the same time, a method for creating a custom collection is defined in the Contact model
public function newCollection(array $models = array())
{
        return new ContactCollection($models);
}

We get an Exception telling us that a Collection is expected, but a ContactCollection comes
Type error: Argument 2 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::match() must be an instance of Illuminate\Database\Eloquent\Collection, instance of App\Collections\ContactCollection given, called in /var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 678

Isn't eager loading compatible with custom collections?
(laravel 5.2)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2016-11-16
@2vtlk

You need to inherit ContactCollectionfrom Illuminate\Database\Eloquent\Collection. Most likely, you are Illuminate\Support\Collectioninherited from or not inherited at all.

2
2vtlk, 2016-11-16
@2vtlk

Yes, indeed, I inherited it from \Illuminate\Support\Collectionand there was a mistake. Thanks to all

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question