Backend Development 26 min read

Laravel Eloquent Relationship Types and Usage Guide

This guide explains Laravel Eloquent's relationship types—including one-to-one, one-to-many, many-to-many, polymorphic and has‑many‑through—showing how to define, query, preload, and manipulate them with PHP code examples and detailed explanations for backend development in applications.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Laravel Eloquent Relationship Types and Usage Guide

Laravel's Eloquent ORM provides a set of relationship methods that make working with related database tables simple and expressive. The most common relationship types are one-to-one, one-to-many, many-to-many, polymorphic, and has‑many‑through.

Defining relationships is done by adding methods to the model class that return the appropriate relation object (e.g., hasOne , hasMany , belongsTo , belongsToMany , morphOne , morphMany , hasManyThrough ). These methods can be chained with query constraints just like a normal query builder.

hasOne('App\Phone');
    }
}
?>

The hasOne example above creates a one‑to‑one link between User and Phone . The foreign key defaults to user_id on the Phone table, but a custom key can be supplied as a second argument.

belongsTo('App\User');
    }
}
?>

One‑to‑many relationships are defined with hasMany . For example, a Post model may have many Comment models:

hasMany('App\Comment');
    }
}
?>

Many‑to‑many relationships use belongsToMany and require a pivot table. The example below shows a User model that can belong to many Role models:

belongsToMany('App\Role');
    }
}
?>

Polymorphic relationships allow a model to belong to more than one other model on a single association. The Comment model can belong to either a Post or a Video :

morphTo();
    }
}

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}
?>

When querying, relationships can be used as query builders to add constraints, count related records, or filter based on existence. Examples include has , whereHas , doesntHave , and withCount methods.

$posts = Post::has('comments')->get();
$posts = Post::whereHas('comments', function ($q) {
    $q->where('content', 'like', 'foo%');
})->get();
$posts = Post::withCount('comments')->get();

Eloquent also supports eager loading with with to avoid N+1 query problems, nested eager loading using dot notation, and constrained eager loading using closures.

$books = Book::with(['author', 'publisher'])->get();
$books = Book::with('author.contacts')->get();
$users = User::with(['posts' => function ($q) {
    $q->where('title', 'like', '%first%');
}])->get();

Inserting or updating related models can be done with save , saveMany , create , createMany , as well as association helpers like associate and dissociate for belongsTo relations. For many‑to‑many pivots, methods such as attach , detach , sync , toggle , and updateExistingPivot manage pivot records and extra attributes.

$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->detach($roleId);
$user->roles()->sync([1, 2, 3]);
$user->roles()->toggle([1, 2]);
$user->roles()->updateExistingPivot($roleId, ['expires' => true]);

Finally, the $touches property on a model can be used to automatically update the updated_at timestamp of related parent models when the child model is saved, keeping caches in sync.

backendORMphpLaravelEloquentRelationships
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.