SyntaxStudy
Sign Up
Laravel Building REST APIs with Laravel
Laravel Beginner 1 min read

Building REST APIs with Laravel

Laravel is an excellent choice for building REST APIs. The api route file (routes/api.php) automatically applies the api middleware group, which includes throttling and stateless session handling. All routes defined there are prefixed with /api by default. API controllers return JSON responses, and Laravel automatically serializes arrays, models, and collections to JSON when returned from a route. API Resources are transformation classes that convert Eloquent models into JSON representations. They decouple your database schema from your API contract, letting you rename attributes, add computed fields, conditionally include relationships, and apply consistent formatting. A resource class extends JsonResource and its toArray() method returns the data to expose. Resource collections handle lists of models. You can create a dedicated collection class with php artisan make:resource PostCollection or use the static collection() method on an existing resource. Collections support pagination links via the paginationInformation() hook. The additional() method adds top-level metadata to the response envelope alongside the data key.
Example
<?php
// Generate: php artisan make:resource PostResource
// app/Http/Resources/PostResource.php

namespace App\Http\Resources;

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

class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'           => $this->id,
            'title'        => $this->title,
            'slug'         => $this->slug,
            'excerpt'      => str($this->body)->limit(160)->toString(),
            'status'       => $this->status,
            'published_at' => $this->published_at?->toIso8601String(),
            'author'       => new UserResource($this->whenLoaded('user')),
            'tags'         => TagResource::collection($this->whenLoaded('tags')),
            'comments_count' => $this->whenCounted('comments'),
            'links'        => [
                'self' => route('api.posts.show', $this->id),
            ],
        ];
    }
}

// In the controller:
// return PostResource::collection(Post::with(['user', 'tags'])->paginate(15));
// return new PostResource($post->load(['user', 'tags']));