Laravel
Beginner
1 min read
Building REST APIs with Laravel
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']));
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel