Laravel Eloquent ORM Tutorial for Beginners: Complete Guide (2026)

By Lyndon Bermoy

Updated on:

Laravel Eloquent ORM Tutorial for Beginners: Complete Guide (2026)

Eloquent is Laravel’s Object-Relational Mapper (ORM). It maps database tables to PHP classes (Models), database rows to class instances, and table relationships to methods you call in plain PHP. Instead of writing SQL for every database operation, you write expressive PHP that reads almost like English.

This tutorial covers Eloquent from the beginning — models, querying, relationships, and common patterns used in real Laravel applications.

What is an ORM?

Without an ORM, database operations look like this:

// Without Eloquent:
$stmt = $pdo->prepare("SELECT * FROM users WHERE active = 1 ORDER BY name LIMIT 10");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

With Eloquent, the same query is:

// With Eloquent:
$users = User::where('active', true)->orderBy('name')->take(10)->get();

Both produce identical SQL. Eloquent adds readability, safety (no manual SQL injection prevention needed), and convenience (automatic timestamps, relationships, casting).

Creating a Model

php artisan make:model Post -m
# -m also creates a migration

This creates app/Models/Post.php:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    // Eloquent assumes table name is plural snake_case of class name: "posts"
    // Override if needed:
    protected $table = 'posts';

    // Mass-assignable fields:
    protected $fillable = ['title', 'content', 'user_id', 'published_at'];

    // Automatic type casting:
    protected $casts = [
        'published_at' => 'datetime',
        'is_featured'  => 'boolean',
        'metadata'     => 'array',  // JSON column auto-decoded
    ];
}

Migrations — Defining the Database Schema

// database/migrations/xxxx_create_posts_table.php
public function up(): void {
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->boolean('is_featured')->default(false);
        $table->timestamp('published_at')->nullable();
        $table->timestamps(); // adds created_at and updated_at
    });
}
php artisan migrate

Basic CRUD with Eloquent

use App\Models\Post;

// CREATE
$post = Post::create([
    'title'   => 'My First Post',
    'content' => 'Post content here...',
    'user_id' => 1,
]);

// Or:
$post = new Post();
$post->title   = 'My First Post';
$post->content = 'Post content here...';
$post->save();

// READ — find by primary key:
$post = Post::find(1);          // Returns null if not found
$post = Post::findOrFail(1);    // Throws ModelNotFoundException if not found

// READ — first result or null:
$post = Post::where('title', 'My First Post')->first();

// READ — all records:
$posts = Post::all();

// READ — with conditions:
$posts = Post::where('is_featured', true)
             ->where('published_at', '<=', now())
             ->orderBy('published_at', 'desc')
             ->paginate(15);

// UPDATE
$post = Post::findOrFail(1);
$post->update(['title' => 'Updated Title']);

// Or:
$post->title = 'Updated Title';
$post->save();

// DELETE
$post = Post::findOrFail(1);
$post->delete();

// Or directly:
Post::destroy(1);
Post::destroy([1, 2, 3]);

Eloquent Relationships

One-to-Many: User has many Posts

// User model:
class User extends Model {
    public function posts(): HasMany {
        return $this->hasMany(Post::class);
    }
}

// Post model:
class Post extends Model {
    public function user(): BelongsTo {
        return $this->belongsTo(User::class);
    }
}

// Usage:
$user  = User::find(1);
$posts = $user->posts;              // All posts by this user (Collection)
$post  = Post::find(1);
$author = $post->user;              // The user who wrote this post

// Create a post belonging to a user:
$user->posts()->create([
    'title'   => 'New Post',
    'content' => 'Content...',
]);

Many-to-Many: Post belongs to many Tags

// Pivot table: post_tag (post_id, tag_id)
// php artisan make:migration create_post_tag_table

// Post model:
public function tags(): BelongsToMany {
    return $this->belongsToMany(Tag::class);
}

// Tag model:
public function posts(): BelongsToMany {
    return $this->belongsToMany(Post::class);
}

// Attach/detach tags:
$post->tags()->attach([1, 2, 3]);
$post->tags()->detach(1);
$post->tags()->sync([2, 3]);    // Removes all except 2 and 3

// Get post tags:
$tags = $post->tags;  // Collection of Tag models

One-to-One: User has one Profile

class User extends Model {
    public function profile(): HasOne {
        return $this->hasOne(Profile::class);
    }
}

$user    = User::find(1);
$profile = $user->profile;   // The user's profile model

Eager Loading — Avoiding N+1 Queries

The N+1 query problem is the most common Eloquent performance mistake. Without eager loading:

// BAD: N+1 — runs 1 query for posts, then 1 query PER POST for user:
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name; // One query per post!
}
// 100 posts = 101 queries

// GOOD: Eager loading — runs 2 queries total:
$posts = Post::with('user')->get();
foreach ($posts as $post) {
    echo $post->user->name; // No additional queries
}
// 100 posts = 2 queries
// Load multiple relationships:
$posts = Post::with(['user', 'tags', 'comments'])->paginate(15);

// Nested eager loading:
$posts = Post::with('comments.user')->get();
// Loads posts → comments → user for each comment

Query Scopes

Scopes let you define reusable query constraints:

class Post extends Model {
    // Local scope — call with ->published()
    public function scopePublished(Builder $query): Builder {
        return $query->where('published_at', '<=', now())
                     ->whereNotNull('published_at');
    }

    // Scope with parameter:
    public function scopeByUser(Builder $query, int $userId): Builder {
        return $query->where('user_id', $userId);
    }
}

// Usage:
$posts = Post::published()->orderBy('published_at', 'desc')->paginate(10);
$myPosts = Post::published()->byUser(auth()->id())->get();

Accessors and Mutators (PHP 8 Style)

use Illuminate\Database\Eloquent\Casts\Attribute;

class Post extends Model {
    // Accessor — transform when reading
    protected function title(): Attribute {
        return Attribute::make(
            get: fn(string $value) => ucwords($value),
        );
    }

    // Mutator — transform when setting
    protected function slug(): Attribute {
        return Attribute::make(
            set: fn(string $value) => str()->slug($value),
        );
    }

    // Both getter and setter
    protected function excerpt(): Attribute {
        return Attribute::make(
            get: fn($value) => $value ?? str()->limit($this->content, 200),
            set: fn($value) => trim($value),
        );
    }
}

Soft Deletes

Soft deletes mark records as deleted without removing them from the database:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {
    use SoftDeletes;
}

// Migration: add deleted_at column
$table->softDeletes();

$post->delete();                    // Sets deleted_at, record still in database
Post::all();                        // Only returns non-deleted posts
Post::withTrashed()->get();        // Includes soft-deleted
Post::onlyTrashed()->get();        // Only soft-deleted
$post->restore();                   // Restores soft-deleted post
$post->forceDelete();               // Permanently removes from database

Common Eloquent Mistakes to Avoid

  • Missing $fillable — without it, Post::create() silently ignores all fields (mass assignment protection)
  • N+1 queries — always use with() when accessing relationships in loops
  • Loading all columns — use select('id', 'title', 'created_at') instead of all() when you do not need all fields
  • Using get() then count() — use count() directly on the query, not on the collection, to avoid loading all records
READ ALSO:   Validation Explained With Beginner Examples

Conclusion

Eloquent transforms database interactions from raw SQL into expressive PHP that reads naturally. Models, relationships, eager loading, scopes, and soft deletes cover the core patterns you will use in every Laravel application. Master these and you will be comfortable working with any Laravel codebase and building database-driven features efficiently.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment