The Complete Production SOP: How to Deploy and Run Laravel 11 Eloquent ORM Advanced Relationships & Scopes in Autonomous AI Agents
Step-by-step SOP to install and run Laravel 11 Eloquent ORM Advanced Relationships & Scopes in Codex, Claude Code, and Cursor. Stop N+1 queries deterministically.
Technical Overview & Architectural Context
Autonomous coding agents frequently default to legacy patterns or brittle anti-patterns when generating Laravel 11 data layer code. Unconstrained agents often introduce severe N+1 query bottlenecks by chaining dynamic relations inside Blade templates or resource collections, omit modern PHP 8.2+ return type hints (e.g., MorphMany, BelongsToMany, HasManyThrough), and fail to configure strict lazy loading protections in development environments. Additionally, LLMs tend to invent non-existent column mappings when defining polymorphic morphTo and morphMany associations without adhering to strict database schema conventions. The 'laravel-11-eloquent-relationships' skill provides deterministic architectural guardrails that enforce Laravel 11 best practices. By mounting this skill into Codex, Claude Code, Cursor, or Windsurf, the agent is constrained to exact procedural SOPs: explicitly declaring return types on relationship methods, applying eager loading constraints using Model::preventLazyLoading(), structuring local query scopes with Builder return types, and establishing self-verifying test commands. This guarantees high-throughput, leak-free database abstraction layers across production Laravel codebases.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into agent runtime directories.
Agent runtimes locate custom skills by scanning root manifest directories such as ~/.agents/skills or project-level configurations like .cursor/rules and .claude/skills. Mounting the verified SKILL.md registers triggers including 'eloquent polymorphic relationship' and 'eager loading with() eloquent', ensuring the model prioritizes strict relationship typing and eager loading conventions over generic defaults.
mkdir -p ~/.agents/skills/laravel-11-eloquent-relationships && curl -fsSL https://askills.dev/api/skills/laravel-11-eloquent-relationships/raw -o ~/.agents/skills/laravel-11-eloquent-relationships/SKILL.md---
name: "laravel-11-eloquent-relationships"
description: "Model complex relational databases with Eloquent relationships, eager loading, and scopes."
metadata:
author: "Taylor Otwell"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "eloquent polymorphic relationship"
- "eager loading with() eloquent"
- "local query scope laravel"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Laravel 11 Eloquent ORM Advanced Relationships & Scopes
Implements Laravel Eloquent: hasMany, belongsTo, belongsToMany with pivot tables, hasManyThrough, polymorphic relationships (morphTo, morphMany), eager loading (with()), and local/global query scopes.
## When to Invoke
Invoke this skill whenever you need to:
- eloquent polymorphic relationship
- eager loading with() eloquent
- local query scope laravel
## Execution SOP & Rules
1. Define relationship method: public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); }.
2. Eager load relations: $posts = Post::with(['author', 'tags'])->paginate(20);
3. Define scope: public function scopeActive(Builder $query): void { $query->where('status', 'active'); }
4. Prevent lazy loading in development: Model::preventLazyLoading(!app()->isProduction());
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.In Cursor and Claude Code, symlink the skill directly into .cursor/rules/laravel-eloquent.mdc or .claude/rules.txt to ensure immediate session-level activation without re-indexing prompts.
Ensure directory permissions grant read access to your local agent user. Restrict file permissions using chmod 644 on SKILL.md to prevent unintentional sandbox modification errors.
Configuring AppServiceProvider & Development Guards
Instruct the agent to configure strict lazy loading violation traps inside Laravel 11's boot pipeline.
Laravel 11 eliminates the traditional Kernel.php structure and minimizes default service providers. The agent must update bootstrap/providers.php and app/Providers/AppServiceProvider.php to invoke Model::preventLazyLoading(!app()->isProduction()) and Model::handleLazyLoadingViolationsUsing(). This forces runtime exceptions during development whenever a relational query fails to declare explicit eager loading.
test -f app/Providers/AppServiceProvider.php && grep -q 'preventLazyLoading' app/Providers/AppServiceProvider.php || echo 'Verification required: enforce strict lazy loading in AppServiceProvider'<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
}
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());
Model::preventAccessingMissingAttributes(! $this->app->isProduction());
}
}Adding Model::preventAccessingMissingAttributes() alongside preventLazyLoading prevents subtle undefined column bugs when agents generate selective field queries with select().
Do not execute artisan config:cache during active local agent development sessions, as cached configs can mask environment-driven conditionals like !app()->isProduction().
Intent Matching & Trigger Invocation
Verify deterministic activation using tested natural language triggers and domain-specific relationship requirements.
Triggering the skill requires using exact architectural terminology matching the frontmatter triggers ('eloquent polymorphic relationship', 'eager loading with() eloquent', 'local query scope laravel'). The agent cross-references the prompt against the SKILL.md manifest, suppressing generic code generation and strictly enforcing explicit return types (e.g., MorphTo, BelongsTo) and Builder-typed query scopes.
Phrase prompts using exact method targets: 'Implement an eloquent polymorphic relationship between Post, Video, and Comment with eager loading with() in the repository layer.'
Avoid vague prompts like 'make a comment system', which may cause the agent to fall back to a generic one-to-many relationship without polymorphic morphTo interfaces.
Verification, Linting & Output Quality Gate
Execute automated static analysis, migration checks, and PHPUnit/Pest test suites to validate relationship integrity.
Before completing execution, the agent must run Laravel Pint, PHPStan/Larastan, and artisan test suites. This quality gate validates that relation return types pass static analysis, pivot tables follow standard Laravel snake_case conventions, and foreign keys have proper cascading constraints.
./vendor/bin/pint --test && ./vendor/bin/phpstan analyse --memory-limit=1G && php artisan test --filter=EloquentRelationshipTest<?php
namespace Tests\Feature;
use App\Models\Comment;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class EloquentRelationshipTest extends TestCase
{
use RefreshDatabase;
public function test_post_has_morph_many_comments_and_eager_loads_cleanly(): void
{
$user = User::factory()->create();
$post = Post::factory()->create(['author_id' => $user->id]);
Comment::factory()->create([
'commentable_id' => $post->id,
'commentable_type' => Post::class,
'user_id' => $user->id,
]);
$retrieved = Post::with(['comments.user', 'author'])->active()->firstOrFail();
$this->assertTrue($retrieved->relationLoaded('comments'));
$this->assertTrue($retrieved->relationLoaded('author'));
$this->assertCount(1, $retrieved->comments);
}
}Ensure Larastan is configured with level 6+ in phpstan.neon so missing generic annotations on Eloquent relationships (e.g., BelongsTo<User, Post>) trigger static analysis warnings.
Running php artisan test without RefreshDatabase or DatabaseTransactions can leave orphan records that invalidate polymorphic foreign key checks in subsequent agent runs.
Real-World Scenario: Implement Polymorphic Tagging and Active Scopes with Strict Lazy Loading Safeguards
“Implement an eloquent polymorphic relationship for Tagging across Article and Course models in Laravel 11. Create the Tag and Tagging models/migrations, define polymorphic morphToMany relationships, add a local query scope laravel for scopePopular(Builder $query, int $threshold), and write an eager loading with() eloquent query in a Controller ensuring Model::preventLazyLoading compliance.”
Runtime Troubleshooting & Failure Modes
Root Cause: The application accessed $post->author inside a serialization step, view, or resource without pre-fetching the relational data via an eager loading with() call, triggering the development guard defined in AppServiceProvider.
$posts = Post::with(['author', 'comments'])->latest()->paginate(20);Root Cause: The agent generated a standard hasMany relationship instead of morphMany, or generated a polymorphic migration omitting the $table->morphs('commentable') helper, leaving out commentable_type and commentable_id columns.
Schema::table('comments', function (Blueprint $table) { $table->morphs('commentable'); });Frequently Asked Questions (Laravel 11 Eloquent ORM Advanced Relationships & Scopes SOP)
Q:Can I use Laravel 11 Eloquent ORM Advanced Relationships & Scopes across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill is defined via an agnostic, standardized SKILL.md manifest. It can be installed into ~/.agents/skills/ for global discovery by Claude Code, symlinked to .cursor/rules/ for Cursor IDE, or referenced in Windsurf workflows without syntax translation.
Q:How does Laravel 11 Eloquent ORM Advanced Relationships & Scopes prevent context window overflow during long agent sessions?
Instead of prompting the model with entire documentation pages, the skill injects only concise, imperative architectural boundaries and high-signal code signatures. This reduces prompt token overhead by over 70% while anchoring the LLM to modern Laravel 11 conventions.
Q:Does this skill require escalated root or container permissions?
No. The skill operates with a verified security score of 98/100. It requires read-only metadata parsing and workspace-scoped file writes (fs_write: 'workspace'), while disabling raw shell execution and network egress in its security manifest.
Ready to equip your autonomous agent with Laravel 11 Eloquent ORM Advanced Relationships & Scopes?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.