API Routes & Resources in PHP

From the Laravel cheat sheet · API Development · verified Jul 2026

API Routes & Resources

Building RESTful APIs

php
// API routes (routes/api.php)
Route::apiResource('posts', PostController::class);

// API resource (transformation)
php artisan make:resource PostResource

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
            'author' => new UserResource($this->user),
        ];
    }
}
💡 Use API resources to transform model data consistently
⚡ whenLoaded() prevents N+1 queries in resources
📌 API routes are automatically prefixed with /api
🔥 Use conditional fields to hide sensitive data

More PHP tasks

Back to the full Laravel cheat sheet