Laravel Order By One Column
To order by using one column you can call the "orderBy()" method and passing in the "column" to order. By default, this will order it in an "Ascending" order. Do refer the code below for this example.
<?php Post::query() ->orderBy('published_at') ->get();
<?php Post::query() ->orderBy('published_at', 'desc') ->get(); // For an alternative you can make use the "orderByDesc" method. Post::query() ->orderByDesc('published_at', 'desc') ->get();
Laravel Order By Two Column
To order by two columns or more you can just chain the method like below.
<?php Post::query() ->orderBy('published_at', 'desc') // DESC ->orderBy('user_id') // ASC ->get(); // For an alternative you can make use the "orderByDesc" method. Post::query() ->orderByDesc('published_at', 'desc') // DESC ->orderBy('user_id') // ASC ->get();
Order By The Eloquent Collection
If you already get the eloquent collection such as by using "all()" and then chaining it with the "sortBy()" method. Do note that this sorting is less efficient than calling the "orderBy" method available to the Query Builder.
<?php // Sort post in ascending order of title $results = Posts::query() ->all() ->sortBy("title"); // Sort post in descending order of title $results = Posts::query() ->all() ->sortByDesc("title");
Leave a reply