Laravel Eloquent ORM

backend
PHP
architecture
zen
Remix

Master Laravel Eloquent ORM with relationships, query optimization, and best practices.

12/8/2025

Prompt

Generate a complete Laravel Eloquent ORM implementation with models, relationships, scopes, and optimized queries for the following application:

Application Overview

Laravel Application Details

  • Application Name: [e.g., Blog, E-commerce, CRM]
  • Laravel Version: [10.x / 11.x / Latest]
  • Database: [MySQL / PostgreSQL / SQLite / MariaDB]
  • Use Cases: [CRUD operations / Complex queries / Reporting / API]

Database Schema

Table 1: [TableName, e.g., users]

  • Model Name: [User]
  • Table Name: [users / custom_name]
  • Timestamps: [Yes / No]
  • Soft Deletes: [Yes / No]

Columns:

  • id: [Primary key, auto-increment]
  • name: [string, required]
  • email: [string, unique, required]
  • password: [string, required]
  • role: [enum: admin, user, etc.]
  • status: [enum: active, inactive, etc.]
  • email_verified_at: [timestamp, nullable]
  • created_at: [timestamp]
  • updated_at: [timestamp]
  • deleted_at: [timestamp, nullable if soft deletes]
  • [Additional columns]

Relationships:

  • Has Many: [posts, comments, orders, etc.]
  • Has One: [profile, settings, etc.]
  • Belongs To Many: [roles, permissions, etc.]

Table 2: [TableName, e.g., posts]

  • Model Name: [Post]
  • Table Name: [posts]
  • Timestamps: [Yes / No]
  • Soft Deletes: [Yes / No]

Columns:

  • id: [Primary key]
  • user_id: [Foreign key to users]
  • title: [string, required]
  • slug: [string, unique]
  • content: [text]
  • excerpt: [text, nullable]
  • status: [enum: draft, published, archived]
  • published_at: [timestamp, nullable]
  • views: [integer, default 0]
  • created_at: [timestamp]
  • updated_at: [timestamp]
  • [Additional columns]

Relationships:

  • Belongs To: [user (author)]
  • Has Many: [comments]
  • Belongs To Many: [tags, categories]
  • Morph Many: [images, if polymorphic]

Table 3: [TableName]

  • Model Name: [ModelName]
  • Table Name: [table_name]
  • Timestamps: [Yes / No]
  • Soft Deletes: [Yes / No]

Columns: [List columns with types and constraints]

Relationships: [List relationships]

[Define 3-10 tables]

Model Configuration

Model 1: [ModelName, e.g., User]

Basic Configuration

  • Fillable Fields: [List fields that can be mass-assigned]
  • Guarded Fields: [List fields protected from mass-assignment, or use [$guarded = []]]
  • Hidden Fields: [password, remember_token, etc.]
  • Visible Fields: [If limiting visible fields]

Casts

  • email_verified_at: [datetime]
  • created_at: [datetime]
  • is_active: [boolean]
  • settings: [array / json]
  • metadata: [object / collection]
  • [Additional casts]

Dates

  • Date Fields: [published_at, verified_at, etc.]
  • Date Format: [Y-m-d H:i:s / Custom]

Relationships

Has Many: [posts]
  • Foreign Key: [user_id]
  • Local Key: [id]
  • Constraints: [onDelete: cascade / set null / restrict]
Has One: [profile]
  • Foreign Key: [user_id]
  • Local Key: [id]
Belongs To Many: [roles]
  • Pivot Table: [role_user]
  • Pivot Fields: [assigned_at, assigned_by]
  • Timestamps on Pivot: [Yes / No]

[Define all relationships]

Scopes

Scope 1: [active]
  • Purpose: [Filter active users]
  • Logic: [where('status', 'active')]
Scope 2: [verified]
  • Purpose: [Filter verified users]
  • Logic: [whereNotNull('email_verified_at')]

[Define 3-8 scopes]

Accessors

Accessor 1: [full_name]
  • Attribute: [full_name]
  • Logic: [Concatenate first_name and last_name]
Accessor 2: [avatar_url]
  • Attribute: [avatar_url]
  • Logic: [Return full URL for avatar]

[Define 2-5 accessors]

Mutators

Mutator 1: [password]
  • Attribute: [password]
  • Logic: [Hash password with bcrypt]
Mutator 2: [email]
  • Attribute: [email]
  • Logic: [Lowercase email before saving]

[Define 1-3 mutators]

Model 2: [ModelName, e.g., Post]

[Same structure as Model 1]

[Define all models]

Query Requirements

Query 1: [Description, e.g., Get published posts with author]

  • Purpose: [Fetch published posts with user relationship]
  • Eager Loading: [user, tags]
  • Filters: [status = published, published_at <= now]
  • Sorting: [published_at desc]
  • Pagination: [15 per page]
  • Performance: [Use select to limit columns]

Query 2: [Description, e.g., Get user with post count]

  • Purpose: [Get users with their post counts]
  • Aggregation: [withCount('posts')]
  • Filters: [has('posts', '>', 5)]
  • Sorting: [posts_count desc]

Query 3: [Description]

  • Purpose: [Purpose]
  • Eager Loading: [Relationships]
  • Filters: [Conditions]
  • Sorting: [Order]
  • Pagination: [Per page]

[Define 5-15 common queries]

Advanced Features

Polymorphic Relationships (if needed)

  • Morphable: [comments, images, tags]
  • Morph To: [commentable, imageable, taggable]
  • Models: [Post, Video, Article can have comments]

Query Scopes with Parameters

Scope: [ofType]

  • Parameter: [type]
  • Logic: [where('type', $type)]

Scope: [createdBetween]

  • Parameters: [start_date, end_date]
  • Logic: [whereBetween('created_at', [$start, $end])]

Global Scopes (if needed)

  • Active Scope: [Automatically filter soft-deleted records]
  • Tenant Scope: [Filter by tenant_id for multi-tenancy]

Observers (if needed)

  • Creating: [Set default values, generate slug]
  • Created: [Send notifications, log activity]
  • Updating: [Validate changes, update related records]
  • Updated: [Clear cache, sync relationships]
  • Deleting: [Check dependencies, archive data]
  • Deleted: [Cleanup related records]

Events (if needed)

  • PostCreated: [Trigger when post is created]
  • UserRegistered: [Trigger on user registration]
  • OrderPlaced: [Trigger on order creation]

Optimization

Eager Loading Strategy

  • N+1 Prevention: [Always eager load relationships in lists]
  • Lazy Eager Loading: [load() for conditional loading]
  • Nested Eager Loading: [posts.comments.user]

Query Optimization

  • Select Specific Columns: [select(['id', 'name', 'email'])]
  • Chunk Large Datasets: [chunk(100) for batch processing]
  • Cursor Pagination: [For large datasets]
  • Index Usage: [Ensure indexes on foreign keys and frequently queried columns]

Caching

  • Cache Queries: [Cache expensive queries]
  • Cache Duration: [1 hour / 24 hours / Custom]
  • Cache Tags: [For cache invalidation]

Migrations

Migration 1: [create_users_table]

  • Table: [users]
  • Columns: [All columns with types and constraints]
  • Indexes: [email unique, status index]
  • Foreign Keys: [None for users]

Migration 2: [create_posts_table]

  • Table: [posts]
  • Columns: [All columns]
  • Indexes: [user_id, status, published_at]
  • Foreign Keys: [user_id references users(id) onDelete cascade]

[Define all migrations]

Seeders

Seeder 1: [UserSeeder]

  • Records: [Create 10 users with factory]
  • Roles: [1 admin, 9 regular users]
  • Verified: [All verified]

Seeder 2: [PostSeeder]

  • Records: [Create 50 posts]
  • Distribution: [Random users, mix of published/draft]

[Define seeders for all tables]

Factories

Factory 1: [UserFactory]

  • Fields:
    • name: [fake()->name()]
    • email: [fake()->unique()->safeEmail()]
    • password: [Hash::make('password')]
    • role: [fake()->randomElement(['admin', 'user'])]

Factory 2: [PostFactory]

  • Fields:
    • user_id: [User::factory()]
    • title: [fake()->sentence()]
    • slug: [Str::slug(title)]
    • content: [fake()->paragraphs(3, true)]
    • status: [fake()->randomElement(['draft', 'published'])]

[Define factories for all models]

Code Generation Requirements

Generate a complete Laravel Eloquent implementation including:

  1. Eloquent Models:

    • Model classes for all tables
    • Fillable/guarded configuration
    • Hidden fields for sensitive data
    • Casts for proper type handling
    • Timestamps and soft deletes configuration
  2. Relationships:

    • All relationship methods (hasMany, belongsTo, belongsToMany, etc.)
    • Pivot table configurations
    • Polymorphic relationships (if needed)
    • Relationship constraints (onDelete, onUpdate)
  3. Scopes:

    • Local scopes for common filters
    • Global scopes (if needed)
    • Dynamic scopes with parameters
  4. Accessors & Mutators:

    • Accessors for computed attributes
    • Mutators for data transformation
    • Attribute casting
  5. Migrations:

    • Migration files for all tables
    • Proper column types and constraints
    • Indexes for performance
    • Foreign key constraints
    • Pivot table migrations
  6. Seeders:

    • Seeder classes for all tables
    • Realistic test data
    • Relationship seeding
  7. Factories:

    • Factory definitions for all models
    • Realistic fake data
    • Relationship factories
  8. Observers (if needed):

    • Observer classes for model events
    • Event handling logic
    • Side effects (notifications, logging, etc.)
  9. Repository Pattern (optional):

    • Repository interfaces
    • Repository implementations
    • Service layer for business logic
  10. Query Helpers:

    • Trait for common query methods
    • Reusable query builders
    • Search functionality
  11. API Resources (if building API):

    • Resource classes for API responses
    • Resource collections
    • Conditional attributes
  12. Documentation:

    • Model relationship diagram
    • Query examples
    • Best practices guide
    • Performance optimization tips

Output production-ready Laravel Eloquent code following best practices with:

  • Proper model configuration and relationships
  • Optimized queries with eager loading
  • Useful scopes for common filters
  • Accessors and mutators for data transformation
  • Complete migrations with proper constraints
  • Seeders and factories for testing
  • N+1 query prevention
  • Proper indexing for performance
  • Type casting for data integrity
  • Soft deletes where appropriate
  • Observer pattern for side effects
  • Clean, readable, and maintainable code
  • PHPDoc comments for IDE support

Tags

laravel
eloquent
orm
php

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In
Laravel Eloquent ORM | vibeprompt.directory