Laravel Resources

Marickian
By -
9 minute read
0
Laravel Resources: Transforming Eloquent Models for APIs

Laravel Resources: Transforming Eloquent Models for APIs

Introduction to Laravel Resources

Laravel resources provide a way to transform your Eloquent models and collections into JSON responses for your APIs. They act as a transformation layer, allowing you to control the format and structure of your API responses, ensuring consistency and flexibility.

Why Use Laravel Resources?

  • Consistency: Ensure consistent formatting across all API responses.
  • Data Control: Select and format only the data you want to expose.
  • Data Transformation: Modify data before returning it, like formatting dates or adding calculated attributes.
  • Conditional Relationships: Include relationships only when needed, optimizing performance.
  • Pagination: Simplify the pagination of API responses.

Creating Resources

You can create a new resource using the make:resource Artisan command:


            php artisan make:resource UserResource
        

This command generates a new resource file in the app/Http/Resources directory.

Resource Structure

A resource class extends Illuminate\Http\Resources\Json\JsonResource and includes a toArray method that defines the format of the returned data.

Example: UserResource


            <?php

            namespace App\Http\Resources;

            use Illuminate\Http\Request;
            use Illuminate\Http\Resources\Json\JsonResource;

            class UserResource extends JsonResource
            {
                public function toArray(Request $request): array
                {
                    return [
                        'id' => $this->id,
                        'name' => $this->name,
                        'email' => $this->email,
                        'created_at' => $this->created_at->format('Y-m-d H:i:s'),
                    ];
                }
            }
        

This example transforms a User model into a JSON object with specific attributes and formatted created_at.

Using Resources in Routes

To use a resource, return an instance of it in your route:


            use App\Http\Resources\UserResource;
            use App\Models\User;

            Route::get('/users/{user}', function (User $user) {
                return new UserResource($user);
            });
        

Resource Collections

For collections of models, use resource collections:


            use App\Http\Resources\UserResource;
            use App\Models\User;

            Route::get('/users', function () {
                return UserResource::collection(User::all());
            });
        

Including Relationships

Use $this->whenLoaded to include relationships conditionally:


            public function toArray(Request $request): array
            {
                return [
                    'id' => $this->id,
                    'name' => $this->name,
                    'email' => $this->email,
                    'posts' => PostResource::collection($this->whenLoaded('posts')),
                ];
            }
        

Conditional Resources

Use $this->mergeWhen and $this->when for conditional attributes:


            public function toArray(Request $request): array
            {
                return [
                    'id' => $this->id,
                    'name' => $this->name,
                    $this->mergeWhen($request->user() && $request->user()->id === $this->id, [
                        'email' => $this->email,
                    ]),
                    'is_admin' => $this->when($request->user() && $request->user()->is_admin, true, false),
                ];
            }
        

Pagination

Laravel resources simplify pagination:


            use App\Http\Resources\UserResource;
            use App\Models\User;

            Route::get('/users', function () {
                return UserResource::collection(User::paginate(10));
            });
        

Resource Wrapping

You can customize the wrapping of resource data using the wrap method:


            UserResource::wrap('user');
        

This wraps the data in a 'user' key.

Additional Tips

  • Use descriptive resource names.
  • Test your API responses thoroughly.
  • Leverage conditional resources for efficient data delivery.

Further Reading

For more details, refer to the official Laravel documentation.

Post a Comment

0Comments

Post a Comment (0)