0
0
Laravelframework~30 mins

API resource classes in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Building an API Resource Class in Laravel
📖 Scenario: You are creating a simple API for a book store. You want to send book data in a clean and organized way to the users of your API.
🎯 Goal: Build a Laravel API resource class that formats book data with specific fields for API responses.
📋 What You'll Learn
Create a Book model with specific attributes
Create a BookResource API resource class
Format the resource to include only selected fields
Return the resource in a controller method
💡 Why This Matters
🌍 Real World
API resource classes help you send clean, consistent data from your Laravel backend to frontend apps or other services.
💼 Career
Understanding API resources is essential for backend developers working with Laravel to build APIs that frontend developers or mobile apps consume.
Progress0 / 4 steps
1
Create the Book model with attributes
Create a Laravel model called Book with these attributes: id, title, author, price, and published_year. Use an array called $fillable to allow mass assignment for title, author, price, and published_year.
Laravel
Need a hint?

The $fillable array lets Laravel know which fields can be filled when creating or updating a model.

2
Create the BookResource API resource class
Create a Laravel API resource class called BookResource inside the App\Http\Resources namespace. Extend the JsonResource class.
Laravel
Need a hint?

API resource classes extend JsonResource to format model data for JSON responses.

3
Define the toArray method to format book data
Inside the BookResource class, add a toArray method that returns an array with these keys and values: 'id' => $this->id, 'title' => $this->title, 'author' => $this->author, and 'year' => $this->published_year. Do not include the price field.
Laravel
Need a hint?

The toArray method controls how the resource data is sent in the API response.

4
Return the BookResource from a controller method
In a controller method called show, return a single book wrapped in the BookResource. Use the variable $book as the model instance.
Laravel
Need a hint?

Wrapping the model instance in the resource class formats the data automatically for the API response.