Laravel's API Resource Features whenLoaded()
Can conditionally include associated data in API responses, optimizing performance by preventing unnecessary database queries.
The following is an example of how to use the whenLoaded()
method:
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'posts' => PostResource::collection($this->whenLoaded('posts')) ]; } }
If the "posts" relationship is not loaded, the posts key will be removed from the response, leaving only "id" and "name".
The following is an example of how to use it in a real scenario:
<?php namespace App\Http\Controllers; use App\Models\Article; use App\Http\Resources\ArticleResource; use Illuminate\Http\Request; class ArticleController extends Controller { public function index(Request $request) { $query = Article::query(); if ($request->boolean('with_author')) { $query->with('author'); } if ($request->boolean('with_comments')) { $query->with(['comments' => fn($query) => $query->latest()]); } return ArticleResource::collection($query->paginate()); } } class ArticleResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'author' => new UserResource($this->whenLoaded('author')), 'comments' => CommentResource::collection( $this->whenLoaded('comments') ), 'latest_comment' => $this->whenLoaded('comments', function() { return new CommentResource($this->comments->first()); }) ]; } }
This implementation demonstrates efficient relationship processing by:
Using whenLoaded()
helps create streamlined and efficient APIs that optimize database queries when needed and maintain flexibility in containing relevant data.
The above is the detailed content of Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading. For more information, please follow other related articles on the PHP Chinese website!