Skip to content

refactor: optimize user data retrieval by using loadCount#9

Merged
nunomaduro merged 1 commit intosupo-dev:mainfrom
kvostyc:refactor/eager-loading-count
Oct 5, 2025
Merged

refactor: optimize user data retrieval by using loadCount#9
nunomaduro merged 1 commit intosupo-dev:mainfrom
kvostyc:refactor/eager-loading-count

Conversation

@kvostyc
Copy link
Contributor

@kvostyc kvostyc commented Oct 3, 2025

the UserController::show() method was executing 3 separate SQL queries to count user relationships (posts, followers, following).

after using loadCount() there is only one query

array:1 [
  0 => array:3 [
    "query" => "select "id", (select count(*) from "posts" where "users"."id" = "posts"."user_id") as "posts_count", (select count(*) from "users" as "laravel_reserved_0" inner join "followers" on "laravel_reserved_0"."id" = "followers"."follower_id" where "users"."id" = "followers"."user_id") as "followers_count", (select count(*) from "users" as "laravel_reserved_1" inner join "followers" on "laravel_reserved_1"."id" = "followers"."user_id" where "users"."id" = "followers"."follower_id") as "following_count" from "users" where "users"."id" in (1)"
    "bindings" => []
    "time" => 0.1
  ]
]

Summary by CodeRabbit

  • Refactor
    • Optimized user profile endpoint by preloading post, follower, and following counts to reduce database queries.
    • Improves load times and scalability, especially for high-traffic profiles.
    • Enhances API response consistency under load.
    • No visible UI changes; count values remain the same but load more reliably.

@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2025

Walkthrough

UserController::show now eager-loads counts for posts, followers, and following using loadCount and reads the resulting posts_count, followers_count, and following_count attributes instead of calling relation count methods at response time.

Changes

Cohort / File(s) Summary
Controller count preloading
app/Http/Controllers/UserController.php
Replace relation count calls with loadCount for posts, followers, following, and use posts_count, followers_count, following_count in the response.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as UserController::show
  participant M as User Model
  participant DB as Database

  Note over C,M: Prepare user data with counts
  C->>M: fetch user (by id/route binding)
  C->>M: loadCount(posts, followers, following)
  M->>DB: SELECT with COUNTs (via eager count)
  DB-->>M: counts attached as *_count
  C->>C: read posts_count, followers_count, following_count
  C-->>Client: JSON response with preloaded counts
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through fields of counts so bright,
Preloading numbers in the light.
No extra trips, just swift delight—
posts_count, friends in tidy sight.
With whiskers twitching, fast and spry,
I ship this patch and thump goodbye. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the main change by indicating a refactor to optimize user data retrieval using loadCount, accurately reflecting the core improvement in the changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b5b970 and 946455b.

📒 Files selected for processing (1)
  • app/Http/Controllers/UserController.php (1 hunks)
🔇 Additional comments (2)
app/Http/Controllers/UserController.php (2)

21-21: Excellent optimization!

Using loadCount() to eager-load relationship counts is the correct approach and will reduce the query overhead from three separate COUNT queries to a single aggregated query.


29-31: LGTM!

The switch from relation count methods to preloaded count attributes is correct and completes the optimization. The response structure remains consistent while eliminating the N+1 query problem.


Comment @coderabbitai help to get the list of available commands and usage tips.

@kvostyc
Copy link
Contributor Author

kvostyc commented Oct 3, 2025

@coderabbitai generate docstrings

@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2025

✅ Actions performed

Docstrings generation started.

coderabbitai bot added a commit that referenced this pull request Oct 3, 2025
Docstrings generation was requested by @kvostyc.

* #9 (comment)

The following files were modified:

* `app/Http/Controllers/UserController.php`
@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2025

Note

Generated docstrings for this pull request at #11

@nunomaduro nunomaduro merged commit 060a7fe into supo-dev:main Oct 5, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants