I am also looking for the best way to do this depending on my example that I am going to detail.
Basically what my controller does is bring the selected category name (from a navbar), and through a scope, I bring the category as an object. Then through the 1:M relationship I bring all the articles of that category. And well, it ends up showing
My issue is that I order them by id in ascending order. And being an article, it shows me the oldest first. What I would need would be to order them in descending order so that it shows me the newest ones first
public function searchCategoria($nombre){
$categoria = Categoria::searchCategoria($nombre)->first();
$articulos = $categoria->articulos()->paginate(5);
$articulos->each(function($articulos){
$articulos->categoria;
$articulos->imagen;
});
dd($articulos);
return view('front/index')->with("articulos",$articulos);
}
This is the result of that dd of $articles
LengthAwarePaginator {#249 ▼
#total: 1
#lastPage: 1
#items: Collection {#250 ▼
#items: array:1 [▼
0 => Articulo {#252 ▶}
]
}
#perPage: 5
#currentPage: 1
#path: "http://emap.net/categorias/Noticias"
#query: []
#fragment: null
#pageName: "page"
}
In my little experience in PHP and more in Laravel, I haven't used any ordering method yet. But I am interested to know if there is a better solution, by orderBy in the relation inside the model or something like that. Because at least in Java sort is always the last resort.
The other one that occurred to me basically is to fetch the category, get its id and search for all the articles with a where and an orderBy. I would not be making use of the relationship, it would be more practical but I don't know if it is the most correct
Taking into account that you already have the collection, I would use the method
sortByDesc()
(applicable to collections) with the date or the desired field before applying the pagination, however I don't have a way to test it at the moment and I don't remember if it is already a collection or still a query at that point.Collection:
Query builder: