0
0
Laravelframework~30 mins

Ordering and grouping in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Ordering and grouping with Laravel Collections
📖 Scenario: You are building a simple Laravel application to manage a list of books in a library. Each book has a title, author, and year of publication.You want to display the books ordered by their publication year and grouped by author.
🎯 Goal: Use Laravel collection methods to order books by year ascending and group them by author.
📋 What You'll Learn
Create a books array where each book has title, author, and year.
Order the books by year ascending using sortBy.
Group the books by author using Laravel collection methods.
Return the grouped and ordered books.
💡 Why This Matters
🌍 Real World
Ordering and grouping data is common in applications like libraries, stores, or any list where you want to organize items by categories and sort them.
💼 Career
Understanding Laravel collections and how to order and group data is essential for backend developers working with Laravel to build efficient and readable data queries.
Progress0 / 4 steps
1
Create the books data array
Create a variable called books that contains an array of associative arrays. Each associative array should have keys 'title', 'author', and 'year' with these exact entries:
{'title' => 'The Hobbit', 'author' => 'J.R.R. Tolkien', 'year' => 1937},
{'title' => '1984', 'author' => 'George Orwell', 'year' => 1949},
{'title' => 'Animal Farm', 'author' => 'George Orwell', 'year' => 1945},
{'title' => 'The Fellowship of the Ring', 'author' => 'J.R.R. Tolkien', 'year' => 1954}.
Laravel
Need a hint?

Use a PHP array with associative arrays inside. Each book is an associative array with keys 'title', 'author', and 'year'.

2
Convert the array to a Laravel collection
Create a variable called booksCollection and set it to a Laravel collection created from the $books array using collect().
Laravel
Need a hint?

Use the collect() helper function to create a collection from the array.

3
Order the books by year ascending
Use the sortBy method on $booksCollection to order the books by the 'year' key in ascending order. Save the result back to $booksCollection.
Laravel
Need a hint?

Use sortBy('year') on the collection to order by the year key.

4
Group the books by author
Use the groupBy method on $booksCollection to group the books by the 'author' key. Save the result back to $booksCollection.
Laravel
Need a hint?

Use groupBy('author') on the collection to group books by author.