Laravel执行用户推荐链查询方法时出现404错误,求排查解决
Why You're Getting a 404 Error & How to Fix It
Hey there! That 404 error is coming directly from the firstOrFail() method in your code. Let me break it down and help you fix it:
The Root Cause
Laravel's firstOrFail() throws a ModelNotFoundException when it can't find a matching record. By default, Laravel converts this exception into a 404 "Page Not Found" response. This is happening because at some point in your loop:
- A
sponsor_usernameexists in a user's record but doesn't match any actual user in the database, or - Your loop runs past the root user and tries to look up a non-existent sponsor, triggering the exception.
On top of that, your loop termination logic has bugs that make this worse:
- The line
if($news = $generation[$x] == $rootParent)mixes assignment (=) and equality check (==) incorrectly. The$newsvariable gets set to a boolean here, and this check only runs whenx > 0—so if the first sponsor you look up is therootParent, your loop will run indefinitely until it hits a missing user. - You don't handle cases where a user might not have a
sponsor_username(like the root user itself), which would also triggerfirstOrFail().
Fixed Code
Here's a revised version of your method that fixes these issues and avoids the 404:
public static function getGeneration($currentParent, $rootParent) { $generation = []; // First, confirm the starting user exists $currentUser = User::where("username", $currentParent)->first(); if (!$currentUser) { // Handle invalid starting user (return empty array or throw a custom exception) return $generation; } while (true) { // Get the sponsor without triggering a 404 if they don't exist $sponsor = User::where("username", $currentUser->sponsor_username)->first(); // Stop the loop if we hit the root parent or a missing sponsor if (!$sponsor || $sponsor->username === $rootParent) { // Add the root to the list if we found it if ($sponsor) { $generation[] = $sponsor->username; } break; } // Add the sponsor to our generation chain $generation[] = $sponsor->username; // Move up the chain: set current user to their sponsor $currentUser = $sponsor; } return $generation; }
Key Improvements
- Replaced
firstOrFail()withfirst()to handle missing users gracefully instead of triggering a 404. - Fixed loop termination logic to stop immediately when hitting the root parent or a missing sponsor.
- Simplified the loop flow (no more tracking the
xindex unnecessarily) for readability. - Added a check for the initial
$currentParentuser to avoid errors if it doesn't exist.
Quick Tips
- If you want to track invalid
sponsor_usernameentries, add aLog::warning()call inside theif (!$sponsor)block to log those issues. - Add a guard clause at the start: if
$currentParent === $rootParent, return an empty array immediately to skip unnecessary looping.
内容的提问来源于stack exchange,提问作者M'Baku
相关产品推荐
相关产品推荐

