Engineering note

How to Structure and Simplify API Responses with Laravel API Resources

Laravel API Resources give a simple way to structure and format the data. This makes it easy to control exactly what information is returned, which can save time and make responses cleaner.

By Published Updated

Article

Step 1: Create an API Resource

First, generate a resource for your model. Let's use a Post model as an example.

CODE SAMPLE Code snippet
php artisan make:resource PostResource
//This creates a PostResource.php file in App\Http\Resources.

Step 2: Define Data Structure in Resource

Open PostResource.php and define the data structure you want to return.

CODE SAMPLE Code snippet
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'author' => $this->user->name,
            'created_at' => $this->created_at->toDateString(),
        ];
    }
}

Here, we’re only returning specific fields: id, title, content, author, and created_at.

Step 3: Use Resource in Controller

Return this resource from your controller to format the response.

CODE SAMPLE Code snippet
use App\Http\Resources\PostResource;
use App\Models\Post;

class PostController extends Controller
{
    public function show($id)
    {
        $post = Post::findOrFail($id);
        return new PostResource($post);
    }
}

Resulting JSON Response

When you call this API, you'll get a formatted JSON response:

CODE SAMPLE Code snippet
{
    "data": {
        "id": 1,
        "title": "Sample Post",
        "content": "This is the content of the post.",
        "author": "John Doe",
        "created_at": "2024-10-26"
    }
}

Laravel API Resources help keep API responses clean and structured, making it easier to manage what data gets sent to clients. Use them to control and format output effectively.