0
0
Laravelframework~5 mins

One-to-one (hasOne, belongsTo) in Laravel

Choose your learning style9 modes available
Introduction

One-to-one relationships connect two things where each item matches exactly one item in the other group. It helps keep related data organized and easy to find.

You have a user and each user has one profile with extra details.
You want to store a car and each car has one registration record.
You keep employee records and each employee has one office location.
You manage books and each book has one unique ISBN detail.
Syntax
Laravel
class User extends Model {
    public function profile() {
        return $this->hasOne(Profile::class);
    }
}

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

hasOne is used on the model that owns the related model.

belongsTo is used on the model that holds the foreign key.

Examples
User has one Profile. This means each user links to one profile.
Laravel
class User extends Model {
    public function profile() {
        return $this->hasOne(Profile::class);
    }
}
Profile belongs to User. This means profile stores the user_id foreign key.
Laravel
class Profile extends Model {
    public function user() {
        return $this->belongsTo(User::class);
    }
}
Get the profile for user with ID 1 using the hasOne relation.
Laravel
$user = User::find(1);
$profile = $user->profile;
Get the user for profile with ID 1 using the belongsTo relation.
Laravel
$profile = Profile::find(1);
$user = $profile->user;
Sample Program

This example shows a User with one Profile. We simulate the relation and print the user's profile bio.

Laravel
<?php

use Illuminate\Database\Eloquent\Model;

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

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

// Simulate fetching user and profile
$user = new User();
$user->id = 1;

$profile = new Profile();
$profile->user_id = 1;
$profile->bio = 'I love coding!';

// Normally, Laravel fetches from DB, here we simulate
// Assume $user->profile() returns $profile

// Output user profile bio
echo "User ID: {$user->id}\n";
echo "Profile Bio: {$profile->bio}\n";
OutputSuccess
Important Notes

Make sure the foreign key column (like user_id) exists in the related table.

Use Laravel's naming conventions or specify keys explicitly if different.

One-to-one relations are great for splitting data into smaller tables for clarity.

Summary

One-to-one links two models where each has exactly one related record.

Use hasOne on the model owning the other, and belongsTo on the model with the foreign key.

This keeps data organized and easy to access in Laravel.