All posts

Fix Infinite Loop in Laravel

Debug and fix infinite loops in Laravel caused by model event listeners, eager loading cycles, and recursive middleware chains.

Infinite Loops in Laravel

Laravel's elegant event system and Eloquent model observers can accidentally create feedback loops that grind your application to a halt.

The Observer Trap

The most common infinite loop in Laravel happens when a model observer triggers the same event it's listening to:

// In UserObserver.php — INFINITE LOOP
public function updated(User $user)
{
    // This triggers another 'updated' event!
    $user->update(['last_activity' => now()]);
}

When updated fires, it calls update(), which fires updated again. This continues until PHP hits its memory limit.

The Fix

Use saveQuietly() or withoutEvents() to break the cycle:

public function updated(User $user)
{
    // Saves without firing events
    $user->saveQuietly();
    // Or use the static method:
    User::withoutEvents(function () use ($user) {
        $user->update(['last_activity' => now()]);
    });
}

Eager Loading Circular References

Another source is circular eager loading in API resources:

// UserResource loads PostResource, PostResource loads UserResource...
class UserResource extends JsonResource {
    public function toArray($request) {
        return [
            'posts' => PostResource::collection($this->posts),
        ];
    }
}

Fix this by conditionally including relations or using whenLoaded():

'posts' => PostResource::collection($this->whenLoaded('posts')),

Bugsly flags these runaway loops quickly — you'll see a spike in memory usage and repeated error events that make the cyclical pattern obvious in the timeline view.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free