Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Lazy) Eager Loading does not work with a Custom Collection in Laravel

Needs

  1. I need to have a CustomCollection
  2. I need to use lazy eager loading

Circumstances & Problem

When I try to lazy eager load by using this construct $posts->load('author'), using a custom collection object, I get the error saying that the collection object does not have the method load.

Code

Post Model:

class Post extends Eloquent
{
    public function  newCollection(array $models = array())
    {
         return new CustomCollection( $models );
    }
}

CustomCollection

class CustomCollection extends Illuminate\Support\Collection
{

    public function specialCollectionMethod()
    {
         return 'something that a standard collection does not provide';
    }
}
like image 417
anglinb Avatar asked Oct 18 '25 08:10

anglinb


1 Answers

I found my mistake!

I realized what I was doing wrong but already wrote the post (above) so I thought I'd fix my mistake:

I realized I need to extend Illuminate\Database\Eloquent\Collection rather than Illuminate\Database\Eloquent\Collection in my CustomCollection. I misread the documentation.

Code

CustomCollection

class CustomCollection extends Illuminate\Database\Eloquent\Collection
{

    public function specialCollectionMethod()
    {
         return 'something that a standard collection does not provide';
    }
}

Documentation

Laravel Collection Documentation

like image 86
anglinb Avatar answered Oct 20 '25 23:10

anglinb