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');
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community