Laravel 12 One-to-One Relationship: A Complete Guide with Examples

Author

Kritim Yantra

Apr 06, 2025

Laravel 12 One-to-One Relationship: A Complete Guide with Examples

In Laravel 12, database relationships help define how different models (tables) interact with each other. A one-to-one relationship is the simplest type, where one record in a table is linked to exactly one record in another table.

Real-World Example

  • A User has one Profile.
  • A Phone belongs to one User.

In this blog, we’ll cover:

  1. What is a One-to-One Relationship?

  1. Setting Up a One-to-One Relationship in Laravel
  1. Creating Migrations & Models
  1. Defining Relationships in Eloquent
  1. Inserting & Retrieving Data

  1. Eager Loading (Optimizing Queries)
  2. Practical Example: User ↔ Profile Relationship

Let’s dive in!


1. What is a One-to-One Relationship?

A one-to-one (1:1) relationship means:

  • One record in Table A is linked to exactly one record in Table B.
  • Example:
    • users table → id, name, email
    • profiles table → id, user_id, bio, phone

Here, one user has one profile, and one profile belongs to one user.


2. Setting Up a One-to-One Relationship

Step 1: Create Laravel Project (Skip if Already Done)

composer create-project laravel/laravel one-to-one-demo
cd one-to-one-demo

Step 2: Configure Database

Edit .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_one_to_one
DB_USERNAME=root
DB_PASSWORD=

3. Creating Migrations & Models

A. Create users Table (Default in Laravel)

Laravel already provides a users migration (database/migrations/xxxx_create_users_table.php).

B. Create profiles Table

Run:

php artisan make:migration create_profiles_table

Edit the migration:

// database/migrations/xxxx_create_profiles_table.php
Schema::create('profiles', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id'); // Foreign key
    $table->string('bio')->nullable();
    $table->string('phone')->nullable();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Run migrations:

php artisan migrate

C. Create Models

Laravel already has a User model (app/Models/User.php).

Now, create a Profile model:

php artisan make:model Profile
// app/Models/Profile.php
protected $fillable = ['user_id', 'bio', 'phone'];

4. Defining the One-to-One Relationship

A. User → Has One Profile

In User.php:

public function profile()
{
    return $this->hasOne(Profile::class);
}
  • hasOne() defines the 1:1 relationship.

B. Profile → Belongs To User

In Profile.php:

public function user()
{
    return $this->belongsTo(User::class);
}
  • belongsTo() defines the inverse relationship.

5. Inserting & Retrieving Data

A. Create a User with a Profile

use App\Models\User;
use App\Models\Profile;

// Create a User
$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
]);

// Create a Profile for the User
$user->profile()->create([
    'bio' => 'Web Developer',
    'phone' => '1234567890',
]);

B. Retrieve User’s Profile

$user = User::find(1);
$profile = $user->profile; // Gets the profile
echo $profile->bio; // Output: "Web Developer"

C. Retrieve Profile’s User

$profile = Profile::find(1);
$user = $profile->user; // Gets the user
echo $user->name; // Output: "John Doe"

6. Eager Loading (Optimizing Queries)

If you fetch multiple users and their profiles, avoid the N+1 problem using with():

// Without Eager Loading (Runs N+1 queries)
$users = User::all();
foreach ($users as $user) {
    echo $user->profile->bio; // Runs a query for each user
}

// With Eager Loading (Runs 2 queries only)
$users = User::with('profile')->get();
foreach ($users as $user) {
    echo $user->profile->bio; // No extra queries
}

7. Practical Example: User ↔ Profile System

Step 1: Create a Route

// routes/web.php
Route::get('/user-profile', function () {
    $user = User::with('profile')->first();
    return view('user-profile', compact('user'));
});

Step 2: Create a Blade View

<!-- resources/views/user-profile.blade.php -->
<h1>{{ $user->name }}</h1>
<p>Bio: {{ $user->profile->bio ?? 'No bio' }}</p>
<p>Phone: {{ $user->profile->phone ?? 'No phone' }}</p>

Step 3: Test in Browser

Run:

php artisan serve

Visit:

http://127.0.0.1:8000/user-profile

You’ll see the user’s profile details!


Conclusion

Key Takeaways:

  1. One-to-One Relationship → One model links to exactly one other model.
  2. hasOne() & belongsTo() → Define the relationship in models.
  3. Eager Loading (with()) → Optimizes database queries.
  4. Practical Use Case → User-Profile system.

Next Steps:

  • Try one-to-many (e.g., User has many Posts).
  • Explore many-to-many (e.g., Users & Roles).

🚀 Happy Coding!

📌 Need help? Drop your questions below! 👇

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Laravel 12 Roles and Permissions Setup: Complete Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel Repository Pattern Explained: Clean Architecture for Developers
Kritim Yantra Kritim Yantra
Mar 09, 2025
Complete Laravel 12 CRUD Guide: Using Laravel UI, Bootstrap & Blade
Kritim Yantra Kritim Yantra
Mar 09, 2025