Mastering Eloquent Relationships

Front
Back
Right
Left
Top
Bottom
RELATIONSHIP
Sanjeewa%20RupasinghePowerful Data Connections

Why Use Relationships in Eloquent?

Whether you're a student learning development or a CEO seeking the pulse of your business, retrieving the right data at the right moment isn't just a tech thing—it's the lifeblood of informed decision-making. Laravel's Eloquent ORM offers elegant solutions to efficiently read and filter data, supporting everything from dashboards to high-traffic apps.1 Getting Started With Eloquent ORM
1:1
Direct Links for Precise Data

One-to-One Relationships

A one-to-one relationship occurs when one record in a table is linked to a single record in another.

Example: Each User has one Profile. 2
Copy to clipboard
// app/Models/User.php
public function profile(): HasOne
{
    return $this->hasOne(Profile::class);
}

// app/Models/Profile.php
public function user(): BelongsTo
{
    return $this->belongsTo(User::class);
}

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

// Getting a user's profile
// For Headless Architecture (API)
$profile = User::with('profile')
            ->find(1);
Show more Show less
1:M
Flexibility for Complex Data

One-to-Many Relationships

A one-to-many relationship means one record is associated with multiple others.

Example: A Post has many Comments 3
Copy to clipboard
// Post.php
public function comments(): HasMany
{
    return $this->hasMany(Comment::class);
}

// Comment.php
public function post(): BelongsTo
{
    return $this->belongsTo(Post::class);
}

// Getting a post with comments
$post = Post::find(1)->comments;

// Getting a post with comments
// For Headless Architecture (API)
$post = Post::with('comments')->find(1);

// Getting a comments with post
$comment = Comment::find(1)->post;

// Getting a comment with post
// For Headless Architecture (API)
$comment = Comment::with('post')->find(1);
m:m
Flexibility for Complex Data

Many-to-Many Relationships

A many-to-many relationship allows multiple records on both sides.

Example: A User can have many Roles, and each Role can have many Users. 4
File icon
Copy to clipboard
// User.php
public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class);
}

// Role.php
public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class);
}

// Assigning roles to a user
// Assigning roles to a user will remove all roles that are not in the array
$user = User::find(1)
    ->roles()
    ->attach([2, 3]);

// Detaching roles from a user
// Detaching roles from a user will remove all roles that are not in the array
$user = User::find(1)
    ->roles()
    ->detach([2, 3]);

// Syncing roles to a user
// Syncing roles to a user will remove all roles that are not in the array
$user = User::find(1)
    ->roles()
    ->sync([2, 3]);

// Syncing roles to a user will remove all roles that are not in the array
$user = User::find(1)
    ->roles()
    ->syncWithoutDetaching([2, 3]);

// Getting a user with roles
$user = User::find(1)
    ->roles;

// Getting a user with roles
// For Headless Architecture (API)
$user = User::with('roles')
    ->find(1);

// Getting a role with users
$role = Role::find(1)
    ->users;

// Getting a role with users
// For Headless Architecture (API)
$role = Role::with('users')
    ->find(1);

Explore project snapshots or discuss custom web solutions.

POLYMORPHIC

Polymorphic Relationships

Polymorphic relationships let one model belong to more than one other model type.

Example: Both Post and Video models can share Comments. 5
File icon
Copy to clipboard
// Comment.php
public function commendable():MorphTo
{
    return $this->morphTo();
}

// Post.php
public function comments(): MorphMany
{
    return $this->morphMany(Comment::class, 'commendable');
}

// Video.php
public function comments(): MorphMany
{
    return $this->morphMany(Comment::class, 'commendable');
}

//create comment for post
$post = Post::find(1);
$comment = $post->comments()->create([
    'content' => 'This is a comment for post',
    // ...
]);

//create comment for video
$video = Video::find(1);
$comment = $video->comments()->create([
    'content' => 'This is a comment for video',
    // ...
]);

//get all comments
$comments = Comment::all();

//get comments for post
$postComments = $post->comments;

//get comments for video
$videoComments = $video->comments;

//update comment for post
$postComment = $post->comments->first();
$postComment->update([
    'content' => 'Update comment for post',
    // ...
]);

//update comment for video
$videoComment = $video->comments->first();
$videoComment->update([
    'content' => 'Update comment for video',
    // ...
]);

//delete comment for post
$postComment = $post->comments->first();
$postComment->delete();

//delete comment for video
$videoComment = $video->comments->first();
$videoComment->delete();

Data models are living artifacts—get them right, and your software lasts a lifetime

Martin Fowler Patterns of Enterprise Application Architecture

Thank You for Spending Your Valuable Time

I truly appreciate you taking the time to read blog. Your valuable time means a lot to me, and I hope you found the content insightful and engaging!
Front
Back
Right
Left
Top
Bottom
FAQ's

Frequently Asked Questions

Yes, use `with(['comments.user'])` to fetch deep relationships efficiently.

Use eager loading (`with()`) for better database performance.

Absolutely — define custom relationship methods and use query scopes as needed.

Eloquent returns null; use the null-safe operator or defaults as needed.

Visit the official https://laravel.com/docs/12.x/eloquent-relationships

  1. Available at:https://laravel.com/docs/12.x/eloquent-relationships
  2. Available at:https://laravel.com/docs/12.x/eloquent-relationships#one-to-one
  3. Available at:https://laravel.com/docs/12.x/eloquent-relationships#one-to-many
  4. Available at:https://laravel.com/docs/12.x/eloquent-relationships#many-to-many
  5. Available at:https://laravel.com/docs/12.x/eloquent-relationships#polymorphic-relationships

Comments are closed