0
0
Laravelframework~30 mins

Resource collections in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Laravel Resource Collection
📖 Scenario: You are creating a simple API for a bookstore. You want to send a list of books in a clean, structured format using Laravel resource collections.
🎯 Goal: Build a Laravel resource collection that transforms a list of books into a JSON response with specific fields.
📋 What You'll Learn
Create an array of books with exact titles and authors
Define a resource collection class for books
Use the resource collection to transform the books data
Return the transformed collection in a controller method
💡 Why This Matters
🌍 Real World
APIs often need to send data in a clean, consistent format. Laravel resource collections help format data before sending it to clients.
💼 Career
Backend developers use resource collections to build APIs that frontend apps or mobile apps consume, ensuring data is structured and easy to use.
Progress0 / 4 steps
1
Create the books data array
Create a variable called books that holds an array with these exact entries: ['title' => 'The Hobbit', 'author' => 'J.R.R. Tolkien'], ['title' => '1984', 'author' => 'George Orwell'], and ['title' => 'To Kill a Mockingbird', 'author' => 'Harper Lee'].
Laravel
Need a hint?

Use a PHP array with associative arrays inside for each book.

2
Create a BookResource collection class
Create a Laravel resource collection class called BookResource that extends Illuminate\Http\Resources\Json\JsonResource. Inside, define the toArray method to return an array with keys 'title' and 'author' from the resource.
Laravel
Need a hint?

Extend JsonResource and override toArray to return title and author.

3
Transform the books array using BookResource collection
Create a variable called bookCollection that uses BookResource::collection($books) to transform the $books array.
Laravel
Need a hint?

Use the static collection method on BookResource with $books.

4
Return the resource collection in a controller method
Create a controller method called index that returns $bookCollection as the response.
Laravel
Need a hint?

Define a function named index that returns the $bookCollection variable.