DEV Community

Aleson França
Aleson França

Posted on

Mastering API resources in Laravel: Transforming your data with power and flexibility

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(),
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

Now when returning an order from the API, we use

return new OrderResource($order);
Enter fullscreen mode Exit fullscreen mode

For collections, Laravel provides a powerful feature.

return OrderResource::collection($orders);
Enter fullscreen mode Exit fullscreen mode

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'
    ];
}

Enter fullscreen mode Exit fullscreen mode

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(),
    ];
}
Enter fullscreen mode Exit fullscreen mode

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')),
    ];
}
Enter fullscreen mode Exit fullscreen mode

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']]);
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

if we want to change this for a specific resource, we can override the wrap property.

<?php

public static $wrap = null;
Enter fullscreen mode Exit fullscreen mode

Pagination with API Resources

When returning a paginated collection, we can use Laravel pagination feature

<?php

return OrderResource::collection(Order::paginate(10));
Enter fullscreen mode Exit fullscreen mode

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,
            ];
        }),
    ];
}
Enter fullscreen mode Exit fullscreen mode

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)