{"id":"521b47f7114adb5a","repo":"laravel/framework","slug":"attempted-to-lazy-load-relation-on-model-c","errorCode":null,"errorMessage":"Attempted to lazy load [{$relation}] on model [{$class}] but lazy loading is disabled.","messagePattern":"Attempted to lazy load \\[(.+?)\\] on model \\[(.+?)\\] but lazy loading is disabled\\.","errorType":"exception","errorClass":"LazyLoadingViolationException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php","lineNumber":624,"sourceCode":"    /**\n     * Handle a lazy loading violation.\n     *\n     * @param  string  $key\n     * @return mixed\n     *\n     * @throws \\Illuminate\\Database\\LazyLoadingViolationException\n     */\n    protected function handleLazyLoadingViolation($key)\n    {\n        if (isset(static::$lazyLoadingViolationCallback)) {\n            return call_user_func(static::$lazyLoadingViolationCallback, $this, $key);\n        }\n\n        if (! $this->exists || $this->wasRecentlyCreated) {\n            return;\n        }\n\n        throw new LazyLoadingViolationException($this, $key);\n    }\n\n    /**\n     * Get a relationship value from a method.\n     *\n     * @param  string  $method\n     * @return mixed\n     *\n     * @throws \\LogicException\n     */\n    protected function getRelationshipFromMethod($method)\n    {\n        $relation = Relation::withConstraintsForNestedRelation(fn () => $this->$method());\n\n        if (! $relation instanceof Relation) {\n            if (is_null($relation)) {\n                throw new LogicException(sprintf(\n                    '%s::%s must return a relationship instance, but \"null\" was returned. Was the \"return\" keyword used?', static::class, $method","sourceCodeStart":606,"sourceCodeEnd":642,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L606-L642","documentation":"When Model::preventLazyLoading() is enabled, accessing a relationship that has not been eager-loaded triggers LazyLoadingViolationException. This is the framework's N+1 protection: it forces developers to load relations via with()/load() instead of firing a query per access.","triggerScenarios":"Enabling preventLazyLoading (default true in many Laravel test bootstraps) then doing $post = Post::first(); $post->comments; without ->with('comments'). Also fires for first()/all()/find() queries that omit the needed relation.","commonSituations":"Forgetting with() when serializing resources or API responses; looping over a collection and touching a relation; new team member not aware eager loading is required; serialization (toArray) of unloaded relations.","solutions":["Eager-load the relation: Post::with('comments')->first().","Lazy-load explicitly where allowed: $post->load('comments') before access.","If intentional, register a lazyLoadingViolationCallback via Model::handleLazyLoadingViolationUsing() to log instead of throw."],"exampleFix":"// before\n$post = Post::first();\n$post->comments; // throws when preventLazyLoading is on\n\n// after\n$post = Post::with('comments')->first();\n$post->comments;","handlingStrategy":"validation","validationCode":"// Ensure relations are loaded before access\nforeach (['comments', 'author'] as $rel) {\n    if (! $post->relationLoaded($rel)) {\n        $post->load($rel);\n    }\n}","typeGuard":"function relationSafe(\\Illuminate\\Database\\Eloquent\\Model $m, string $rel): bool\n{\n    return $m->relationLoaded($rel) || ! $m->isRelation($rel);\n}","tryCatchPattern":"try {\n    return $post->comments;\n} catch (\\Illuminate\\Database\\LazyLoadingViolationException $e) {\n    $post->load($e->relation);\n    return $post->{$e->relation};\n}","preventionTips":["Eager-load relations at query time with with().","Keep preventLazyLoading enabled in non-production to find N+1s early.","Use a lazyLoadingViolation callback (Model::handleLazyLoadingViolationUsing) to log instead of throw in prod."],"tags":["eloquent","lazy-loading","relationship","performance","n-plus-one"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}