API Resources in Laravel

What are API Resources in Laravel?

API Resources in Laravel convert Eloquent models and collections into JSON. This ensures consistent and structured API responses. They make it easier to customize the structure of the data returned by your application.


Origin

API Resources were introduced to aid API development in Laravel. They give developers flexibility in displaying data in JSON responses.


Why are API Resources Used?

  1. Consistent API Responses: Ensure API responses have a consistent structure.
  2. Simplified Data Formatting: Minimize the need for manual data modification.
  3. Reusable Transformations: Generate reusable resource classes for models or collections.

Best Practices.

  1. Use Resources for API responses: Don't return raw Eloquent models in API responses.
  2. Customize using the 'toArray' Method: Use the resource's 'toArray' method to define the JSON response structure.
  3. Use Relationships: Use Eloquent relationships to integrate related models into the resource.

Example in Action

To create an API Resource for a Post model:

php artisan make:resource PostResource

In the generated class:

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->author->name,
        ];
    }
}

Use the resource in your controller:

use App\Http\Resources\PostResource;

public function show(Post $post)
{
    return new PostResource($post);
}

Read more