So here is the scenario You can paginate a set like this ~~ $books = Books::where('price', 1)->paginate(10); ~~ This returns a \Illuminate\Support\Collection
but if you try to call $books->load('author') it complains that \Illuminate\Support\Collection has no method called "load"
It seems silly but a paginated result is the perfect thing to eager load. So I had to do a workaround by creating a new dummy collection that I then use to paginate
$col = new \Illuminate\Database\Eloquent\Collection();
foreach ($books as $book) {
$col->add($book);
}
$col->load('author');
$links = $books->links();
I do this because in the view I can do $book->author without worrying about the multiple queries. Doesn't that seem silly? Can anyone explain why they did it like this?
I don't understand your question. Do you keep all the books in your $books? You should paginate in ORM, not in ready collection.
If you want to eager load authors, you should use with()
method, like this:
$books = Book::with('author')
->orderBy('title')
->skip(20)
->take(10)
->get(['title', 'excerpt']);
I learned that I don't need to operate on collections of models very often. Sometimes I do, but generally most of stuff you should do on the query itself.
@rickshawhobo - Just as a point of support, I'm in the same boat as you here. I want to be able to get my result set, THEN add the eager loading so I'm not loading the relationships on ALL of the records, then paginating them.
The solution is this
$books = Book::with('author')->paginate(10);
The problem is that you just can't lazy eager load with pagination. I'm not sure why they made that decision.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community