Support the ongoing development of Laravel.io →
posted 7 years ago
Last updated 2 years ago.
0

Hi Mat,

Yeah there is. You can order the books when retrieving them from the DB or order the Laravel collection after it is retrieved. I recommend you to order them when retrieving them from the database. To do so use orderBy.

@foreach ($author->books()->orderBy('title')->get() as $book)

Note that

$author->books;

is the same as

$author->books()->get();

when invoked the first time. The explicit get will query the database every time, while the magic property stores the value of the books and makes a single query if used multiple times.

I think you can make the books ordered by default by adding the orderBy in the books() method.

return $this->hasMany('App\Books', 'id_author', 'id')->orderBy('title');
0

Also make sure that when you get the authors from the database you get them together with the books.

$authors = Author::with('books')-...>get();

to avoid numerous queries.

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Mat Mat cardos Joined 18 Aug 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.