Eloquent Relationships

Eloquent Relationships

One to One

One record “owns” exactly one other record.

Examples

  • User ↔ Profile
  • Location↔ Coordinates
  • Order ↔ Invoice

How it works

  • Owner model defines hasOne().
  • Dependent model defines belongsTo() (the inverse).
  • Foreign key lives on the dependent table (e.g., profiles.user_id).

Here’s an example for One to One relationship: Here
Look at the Employer <-> User relationship and just navigate to the corresponding migrations to see how the Database is built up.

PHP
// app/Models/User.php
class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function employer()
    {
        return $this->hasOne(Employer::class); // forward
    }
}

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

One to Many

One record has many dependents.

Examples

  • Post → Comment
  • Category → Product
  • User → Comment

How it works

  • Parent defines hasMany().
  • Child defines belongsTo() (inverse).
  • Foreign key on the child table (e.g., comments.post_id).

Here’s an example for One to Many relationship: Here
Look at the User -> Book / Note relationship and just navigate to the corresponding migrations to see how the Database is built up.

PHP
// app/Models/User.php
class User extends Authenticatable
{
    protected $guarded = [];
    
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    public function books()
    {
        return $this->hasMany(Book::class); // forward
    }
    
     public function notes()
    {
        return $this->hasMany(Note::class); // forward
    }
}

// app/Models/Note.php or Book.php
class Note extends Model { // or Book
        
    protected $table = 'notes'; // or books

    protected $guarded = [];

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

Many to Many

Records on both sides can relate to many on the other side via a pivot table.

Examples

  • User ↔ Role (pivot: role_user)
  • Post ↔ Tag (pivot: post_tag)
  • Student ↔ Course (pivot: course_student)

How it works

  • Both sides define belongsToMany().
  • Pivot table typically uses snake_cased singular model names in alphabetical order and holds the two FKs (optionally extra columns like assigned_at).
  • You can use withTimestamps() and withPivot() to access pivot data.

Here’s an example for Many to Many relationship: Here
Look at the Job <-> Tag relationship and just navigate to the corresponding migrations to see how the Database is built up.

PHP
// app/Models/Job.php
class Job extends Model {
    public function tag(string $name): void
    {
        $tag = Tag::firstOrCreate(['name' => $name]);

        $this->tags()->attach($tag);
    }

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

// app/Models/Tag.php
class Tag extends Model {
    public function jobs(): BelongsToMany
    {
        return $this->belongsToMany(Job::class); // inverse
    }
}

Has Many Through

“Skip through” an intermediate model to reach a distant model in a single relationship.
Important: Works when the middle model has a FK to the parent and the final model has a FK to the middle model. It does not work through a many-to-many pivot.

Examples

  • Employer→ Job through User
    • users.employer_id, jobs.user_id
  • Author → Comment through Post
    • posts.author_id, comments.post_id
  • Owner → Service through Car
    • cars.owner_id, services.car_id

How it works

  • Parent defines hasManyThrough(Final::class, Through::class).
  • There isn’t a built-in “inverse” like belongsToThrough() in core Eloquent. You typically navigate back using the normal belongsTo() on the intermediate and final models (or use a community package if you truly need a reverse-through).

Here’s an example for has Many Through relationship: Here
Look at the User -> Employer -> Job relationship and just navigate to the corresponding migrations to see how the Database is built up.

PHP
// app/Models/User.php
class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function jobs(): HasManyThrough
    {
        return $this->hasManyThrough(Job::class, Employer::class); // forward
    }
}

// app/Models/Employer.php
class Employer extends Model 
{
    public function jobs(): HasMany
    {
        return $this->hasMany(Job::class); // forward
    }
}

// app/Models/Job.php
class Job extends Model {

    public function employer(): BelongsTo
    {
        return $this->belongsTo(Employer::class); // inverse
    }
}

Here’s how you would test it in “php artisan tinker” for example:

PHP
use App\Models\User; 

$user = User::find(2); // or replace the number with any given user id

$user->jobs; // if it's setup correctly then you should get all the Jobs from the specified User above

Another example:

PHP
// Author -> Comments through Posts
class Author extends Model {
    public function comments() {
        return $this->hasManyThrough(Comment::class, Post::class);
    }
}
class Post extends Model {
    public function author()  { return $this->belongsTo(Author::class); }
    public function comments(){ return $this->hasMany(Comment::class); }
}
class Comment extends Model {
    public function post() { return $this->belongsTo(Post::class); }
}

Example usage:

PHP
$country = Country::with('posts')->find(1);
$country->posts; // all posts written by users from this country

$author = Author::find(10);
$recent = $author->comments()->latest()->take(5)->get();

Polymorphic Relations

Polymorphic is not as difficult of a word as it may seem, you only need to take it apart. Poly comes from the ancient Greek word “polýs” meaning many or much, so an undefined quantity from 1 to x (any given amount). You might’ve heard Poly before in the form of Polygon or it sometimes is also used as an abbreviation of Polyester. Morphic comes from morph, having the ability of taking form of a given object or organism, kind of like a putting on a mask so its not its real form even tough it looks like it. So if we put the two meaning together then we get something having the ability to morph into many different forms.
And that’s exactly what a Polymorphic Relation is, it’s like a One to One or One to Many Relation but what the Relation is, isn’t defined.
Here are a few examples:

A single model (e.g., Comment) can belong to more than one other model on a single association, using *_id + *_type.

Examples

  • Comment on Post and on Video (one-to-many polymorphic)
  • Like on Post and on Video (one-to-many polymorphic)
  • Image for User and for Product (one-to-one polymorphic avatar/thumbnail)

How it works

  • Child defines morphTo() (inverse).
  • Each parent defines morphOne() or morphMany() with the same morph name (e.g., 'commentable', 'likeable', 'imageable').
  • Child table has morph_name_id and morph_name_type columns (e.g., commentable_id, commentable_type).

Example 1 – Comments on Posts & Videos:

PHP
// app/Models/Comment.php
class Comment extends Model
{
    protected $fillable = ['body'];

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

// app/Models/Post.php
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable'); // forward
    }
}

// app/Models/Video.php
class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable'); // forward
    }
}

Example usage:

PHP
$post = Post::find(1);
$post->comments()->create(['body' => 'Great post!']);

$video = Video::find(5);
$video->comments()->create(['body' => 'Nice edit!']);

$comment = Comment::first();
$parent = $comment->commentable; // Post or Video instance

Migration pattern for polymorphic:

PHP
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->text('body');
    $table->nullableMorphs('commentable'); // adds commentable_id & commentable_type (indexed)
    $table->timestamps();
});

Example 2 – Likes on Posts & Videos:

PHP
// app/Models/Like.php
class Like extends Model
{
    protected $fillable = ['user_id'];

    public function likeable()
    {
        return $this->morphTo(); // inverse
    }
}

// app/Models/Post.php
class Post extends Model
{
    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable'); // forward
    }
}

// app/Models/Video.php
class Video extends Model
{
    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable'); // forward
    }
}

Example usage:

PHP
$post->likes()->create(['user_id' => auth()->id()]);
$video->likes()->create(['user_id' => auth()->id()]);

// count likes across different likeables
$total = Like::whereMorphedTo('likeable', Post::class)->count(); // likes on posts only

Example 3 – Single Image for User or Product:

PHP
// app/Models/Image.php
class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}

// app/Models/User.php
class User extends Model
{
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}

// app/Models/Product.php
class Product extends Model
{
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}

Many to Many Polymorphic Relations

A single “tag-like” model can belong to multiple other models and each of those models can have many of them, via a polymorphic pivot.

Typical use-cases (3 examples)

  • Tag on Post and on Video
  • Category on Product and on Service
  • Skill on User and on Job

How it works

  • Central model (e.g., Tag) defines morphedByMany() once per related type.
  • Each related model defines morphToMany() back to the central model using the same morph name (e.g., 'taggable').
  • Pivot table is typically the singular central model + morph name, e.g., taggables with columns: tag_id, taggable_id, taggable_type.

Example – Tags for Posts & Videos:

PHP
// app/Models/Tag.php
class Tag extends Model
{
    protected $fillable = ['name'];

    // inverse sides for each taggable model
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable'); 
    }

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

// app/Models/Post.php
class Post extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')  // forward
            ->withTimestamps()
            ->withPivot('added_by');
    }
}

// app/Models/Video.php
class Video extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->withTimestamps();
    }
}

Example usage:

PHP
$post->tags()->attach($tagId, ['added_by' => auth()->id()]);
$video->tags()->sync([1, 2, 3]); // keep only tags [1,2,3]

$tag = Tag::with(['posts', 'videos'])->find(1);
$tag->posts;  // all posts with this tag
$tag->videos; // all videos with this tag

Migrations

PHP
Schema::create('tags', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();
    $table->timestamps();
});

Schema::create('taggables', function (Blueprint $table) {
    $table->foreignId('tag_id')->constrained()->cascadeOnDelete();
    $table->morphs('taggable'); // taggable_id, taggable_type (indexed)
    $table->timestamps();
    $table->unique(['tag_id', 'taggable_id', 'taggable_type']); // optional dedupe
});

Extra Tips for Polymorphic Relations:

  • Inverse names must match: morphMany(Comment::class, 'commentable') ↔︎ morphTo() expecting commentable_id & commentable_type.
  • Query by type: whereMorphedTo('likeable', Post::class) filters polymorphic rows to a single parent type.
  • Eager load across types: Comment::with('commentable')->latest()->get().
  • Soft deletes: If you use soft deletes on the parent, think about cascading cleanup for polymorphic children.
  • Performance: Polymorphic *_type stores a class string by default; you can map morph types to shorter aliases with Relation::enforceMorphMap([...]).

choosing Keys

In Laravel a lot of the code gets pulled automatically in the background. For that to work there are default it will refer to, for example: user_id
If you don’t use the default then you will need to adjust your code a bit. Here’s how:

PHP
// hasOne / hasMany
return $this->hasMany(Comment::class, 'post_id', 'id');
// belongsTo
return $this->belongsTo(Post::class, 'post_id', 'id');
// belongsToMany
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
// hasManyThrough (explicit keys)
return $this->hasManyThrough(
    Post::class, User::class,
    'country_id',   // FK on users table...
    'user_id',      // FK on posts table...
    'id',           // local key on countries
    'id'            // local key on users
);

Tags: