Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Laravel

Laravel One-to-One and One-to-Many Relationships

Define hasOne, belongsTo, hasMany relationships and query related models with Eloquent.

Laravel One-to-One and One-to-Many Relationships — a practical guide to Laravel eloquent relationships with clear examples you can reuse in real projects.

Laravel Tutorial Series (24/27). Prefer one page? Read the complete Laravel tutorial (all 27 topics).

Short description

Relationships describe how models connect — a user has a profile (one-to-one), a user has many posts (one-to-many).

One-to-one

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

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

One-to-many

// User.php
public function posts()
{
    return $this->hasMany(Post::class);
}

// Post.php
public function user()
{
    return $this->belongsTo(User::class);
}
$user->posts;                 // collection
$post->user->name;            // related parent
Post::with('user')->get();    // eager load

Create related models

$user->posts()->create([
    'title' => 'New post',
    'body'  => 'Content here',
]);

Leave a reply

Your email address will not be published. Required fields are marked *