Topics Eloquent ORM Models & Relationships
intermediate 18 min read

Models & Relationships

Creating Eloquent models, defining relationships, eager loading, and the N+1 query problem.

Eloquent Models

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Post extends Model
{
protected $fillable = ["title", "body", "user_id"];

protected function casts(): array
{
return [
"published_at" => "datetime",
"is_published" => "boolean",
"metadata" => "array",
];
}

public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}

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

Relationship Types

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

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

// Many to Many
public function roles(): BelongsToMany {
return $this->belongsToMany(Role::class)
->withPivot("assigned_at")
->withTimestamps();
}

// Has Many Through
public function comments(): HasManyThrough {
return $this->hasManyThrough(Comment::class, Post::class);
}

// Polymorphic
public function images(): MorphMany {
return $this->morphMany(Image::class, "imageable");
}

Eager Loading

// Prevent N+1
$posts = Post::with("user", "comments")->get();

// Nested eager loading
$posts = Post::with("comments.user")->get();

// Lazy eager loading
$posts = Post::get();
$posts->load("user");

// Default eager loading on model
protected $with = ["user"];

Laravel 13: Model Improvements

Laravel 13 introduces #[Fillable] and #[Appends] attributes replacing $fillable and $appends properties for declarative configuration directly on the model class.

Examples

<?php
use App\Models\User;
use App\Models\Post;

// Eager load relationships
\$users = User::with(['posts' => function (\$query) {
    \$query->where('is_published', true);
}])->get();

foreach (\$users as \$user) {
    echo \$user->name . ' has ' . \$user->posts->count() . ' posts.';
}

Your Notes

Sign in to take notes for this lesson.

Quiz

Eloquent ORM Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.