If you are just getting started with Laravel, make sure to check out this introduction course here: Whenever I have the chance, I would use the orderBy method, but it is still quite handy to be able to easily order your results on a collection level. $posts = Post::all()->sortByDesc( "name") Similar to the Eqluent methods, you can sort by ascending order using the sortBy method and sort by descending order using the sortByDesc method:Īlternatively, you could chain the method too: // Ascending This means that at a collection level, you could use the available sortBy method rather than the orderBy method, which is available at the query level. But you could also use the available collection methods to order the contents of a collection too. To summarize the above, you can use the Eloquent methods while building your query, this would be a more efficient way of sorting your results. Ordering the results on a collection level with all() And once you have the collection ready, you would need to use the available Laravel collection methods rather than the eloquent methods. However, if you use all() rather than get() you would first get all of the entries from your Database and store them in a collection. To learn more about SQL, you can check out this free eBook on how to get started with SQL here. So as you can see, the orderBy method actually represents the ORDER BY function in SQL.īy default, Eloquent will order by ascending, but you could also order by descending by using the orderByDesc() method: $posts = Post::orderByDesc( 'name')->get() The actual query, you would get the following output: "select * from `posts` order by `name` asc" If you added the toSql() method instead of the get() and used dd to print out the output as follows: $posts = Post::orderBy( 'name')->toSql() When getting the results from the database, we could use the orderBy method followed by the get method: $posts = Post::orderBy( 'name')->get() Let's say that we wanted to sort all of our posts by name. Learn more about the DevDojo sponsorship program and see your logo here to get your brand in front of thousands of developers. View Website Learn how to code your own blockchain and create your own crypto-currency with the CoinCamp interactive and fun online training platform. Ordering the results on a query levelīefore we cover how to sort the results on a collection level, let's first briefly cover how we would sort the results on a query level. We will use a model called Post as an example in this tutorial. Or you could use this awesome script to do the installation:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |