Laravel provides tools to make API development easier, and one of the most powerful ones is API Resources. They allow us to transform and structure data before sending it to client, ensuring flexibility and consistency in API response.
What Are API Resources?
API Resources are specialized Laravel classes that help transform models and collections into well-structured JSON responses. They allow us to separate application logic from response formatting, giving us greater control over the data we expose.
Creating an API Resource
We can generate a Resource using Artisan:
php artisan make:resource OrderResource
This will create a file in app/Http/Resources/OrderResource.php
, where we define how the data should be structured
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'total' => $this->total,
'status' => $this->status,
'created_at' => $this->created_at->toDateTimeString(),
];
}
}
Now when returning an order from the API, we use
return new OrderResource($order);
For collections, Laravel provides a powerful feature.
return OrderResource::collection($orders);
Advanced Uses of API Resources
Customizing Responses with with
We can add extra metadata to responses using the with
method
<?php
public function with(Request $request)
{
return [
'api_version' => '1.0.0',
'author' => 'My Name'
];
}
Conditionally Hiding Fields
We can hide sensitive data based on the user's role
<?php
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'total' => $this->total,
'status' => $this->when($request->user()->isAdmin(), $this->status),
'created_at' => $this->created_at->toDateTimeString(),
];
}
Handling Relationships in API Resources
If an order belongs to a customer, we can automatically include customer details
<?php
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'total' => $this->total,
'customer' => new CustomerResource($this->whenLoaded('customer')),
];
}
This ensures that the customer
relationship is only loaded when explicitly requested, avoiding unnecessary queries.
Customizing JSON Structure with additional
We can add extra information without modifying toArray
<?php
return (new OrderResource($order))->additional(['meta' => ['version' => '1.0.0']]);
Data Wrapping
By default, Laravel wraps resource responses inside a data
key. We can disabled this globally in AppServiceProvider
<?php
public function boot(): void
{
JsonResource::withoutWrapping();
}
if we want to change this for a specific resource, we can override the wrap
property.
<?php
public static $wrap = null;
Pagination with API Resources
When returning a paginated collection, we can use Laravel pagination feature
<?php
return OrderResource::collection(Order::paginate(10));
This automatically adds metadata like links
and meta
. Providing useful pagination details.
Working with pivot
in API Resources
When dealing with many-to-many
relations, we can access pivot
table data
<?php
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'total' => $this->total,
'pivot' => $this->whenPivotLoaded('order_product', function () {
return [
'quantity' => $this->pivot->quantity,
'price' => $this->pivot->price,
];
}),
];
}
This ensures pivot table data is only loaded when necessary.
Conclusion
API Resources are an incredible tool for structuring Laravel API responses. With features like conditional data transformation, metadata inclusion, relationship, handling, pagination and pivot
support, they make API development more flexible and organized.
To dive deeper into Laravel API Resources, check out the official doc: Laravel - API Resources
If you're looking for best practices and broader API design principles, here are some great articles:
If you're not using API Resources in Laravel yet, now is the time to start! 🚀
Top comments (0)