Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?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']));
Result
Open