Skip to main content

Eloquent Models and Relationships

10/28
Chapter 3 Eloquent ORM and Database Mastery

Eloquent Models and Relationships

25 min read Lesson 10 / 28

Eloquent: Laravel's Beautiful ORM

Eloquent maps database tables to PHP objects with an expressive, intuitive API. Each model represents a table, and each instance represents a row.

Defining a Model

php artisan make:model Post -mfc
class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'slug', 'body', 'excerpt',
        'user_id', 'category_id', 'is_published', 'published_at',
    ];

    protected $casts = [
        'is_published' => 'boolean',
        'is_featured' => 'boolean',
        'published_at' => 'datetime',
        'metadata' => 'array',
    ];
}

Relationships

BelongsTo — A post belongs to an author:

public function author(): BelongsTo
{
    return $this->belongsTo(User::class, 'user_id');
}

HasMany — A user has many posts:

public function posts(): HasMany
{
    return $this->hasMany(Post::class);
}

BelongsToMany — Posts have many tags through a pivot:

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

HasOne — A user has one profile:

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

Using Relationships

// Eager loading (prevents N+1 queries)
$posts = Post::with(['author', 'tags', 'category'])->get();

// Accessing
$post->author->name;
$post->tags->pluck('name');

// Creating through relationships
$user->posts()->create([
    'title' => 'My New Post',
    'body' => 'Content here...',
]);

// Querying relationships
$publishedPosts = $user->posts()->where('is_published', true)->get();
$usersWithPosts = User::has('posts', '>=', 5)->get();
$popular = User::withCount('posts')->orderByDesc('posts_count')->get();

Accessors and Mutators

// Accessor — computed property
protected function readingTime(): Attribute
{
    return Attribute::get(function () {
        return ceil(str_word_count($this->body) / 200);
    });
}

// Usage: $post->reading_time => 5

Eloquent makes database interactions feel natural while keeping your code clean and maintainable.