Home > Backend Development > PHP Tutorial > Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading

Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading

Robert Michael Kim
Release: 2025-03-06 02:03:08
Original
912 people have browsed it

Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading

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'))
        ];
    }
}
Copy after login

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());
            })
        ];
    }
}
Copy after login

This implementation demonstrates efficient relationship processing by:

  • Dynamic relationship loading based on request parameters
  • Conditional including
  • Optimized query loading for improved performance

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template