Deep Dive into Laravel Eloquent Relationships and Functions

Laravel Eloquent is a very powerful ORM tool. In this article we will focus on the functions and all types of relationships that Eloquent supports. We will skip the model creation and directly go to the parts that matter for real world applications. This is written in simple non native English with no special characters.


Basic Usage of Eloquent

Once you have models and tables set up you can start using Eloquent. Some basic functions you can use on any model are:

User::all();
User::find(1);
User::where('name', 'Ali')->first();
User::create(['name' => 'Ali', 'email' => 'ali@email.com']);

One to One Relationship

This means one record is linked to exactly one other record.

In User model:

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

In Profile model:

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

Usage:

$user = User::with('profile')->find(1);
echo $user->profile->phone;

One to Many Relationship

This means one record is linked to many records.

In Post model:

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

In Comment model:

public function post() {
    return $this->belongsTo(Post::class);
}

Usage:

$post = Post::with('comments')->find(1);
foreach ($post->comments as $comment) {
    echo $comment->body;
}

Many to Many Relationship

This means both sides have multiple records.

In User model:

public function roles() {
    return $this->belongsToMany(Role::class);
}

In Role model:

public function users() {
    return $this->belongsToMany(User::class);
}

Usage:

$user = User::with('roles')->find(1);
foreach ($user->roles as $role) {
    echo $role->name;
}

Also you can add extra data in pivot table:

public function roles() {
    return $this->belongsToMany(Role::class)->withPivot('assigned_at');
}

Has Many Through Relationship

Useful when you want to get data through another relation.

In Country model:

public function posts() {
    return $this->hasManyThrough(Post::class, User::class);
}

Now you can get all posts for a country directly:

$country = Country::find(1);
foreach ($country->posts as $post) {
    echo $post->title;
}

Polymorphic One to Many

When one model can belong to more than one other model.

In Comment model:

public function commentable() {
    return $this->morphTo();
}

In Post model:

public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
}

In Video model:

public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
}

Now comments can belong to posts or videos.


Polymorphic Many to Many

When many models can share many tags.

In Tag model:

public function posts() {
    return $this->morphedByMany(Post::class, 'taggable');
}

public function videos() {
    return $this->morphedByMany(Video::class, 'taggable');
}

In Post model:

public function tags() {
    return $this->morphToMany(Tag::class, 'taggable');
}

In Video model:

public function tags() {
    return $this->morphToMany(Tag::class, 'taggable');
}

Extra Eloquent Functions

append custom attributes

In model:

protected $appends = ['full_name'];

public function getFullNameAttribute() {
    return $this->first_name . ' ' . $this->last_name;
}

hidden and visible

protected $hidden = ['password'];
protected $visible = ['name', 'email'];

withCount

$users = User::withCount('posts')->get();
echo $users[0]->posts_count;

exists and doesntExist

$users = User::whereHas('posts')->get();
$users = User::whereDoesntHave('posts')->get();

touch

protected $touches = ['parent'];

Summary

In this article we explored the main relationships in Laravel Eloquent and how to use them in practical ways. One to one one to many many to many polymorphic and through relationships are useful in almost every project. Eloquent makes it easy to use complex relations with clean syntax. Keep practicing and you will see the real power of Laravel ORM.

0
Subscribe to my newsletter

Read articles from Rameez Karamat Bhatti directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rameez Karamat Bhatti
Rameez Karamat Bhatti

I am a full-stack developer currently working with PHP, Laravel, Tailwind CSS, and Livewire. I also work extensively with Inertia.js to build seamless single-page applications using Vue.js and Laravel. I have experience building reactive frontends with Vue.js and React, and robust backends with REST APIs. I am highly proficient in MySQL, MongoDB, and also comfortable working with PostgreSQL for relational data projects. My focus is on clean, scalable code and building user-focused digital products.