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:
- What is a One-to-One Relationship?
- Setting Up a One-to-One Relationship in Laravel
- Creating Migrations & Models
- Defining Relationships in Eloquent
- Inserting & Retrieving Data
- Eager Loading (Optimizing Queries)
- 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:
userstable →id,name,emailprofilestable →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:
- One-to-One Relationship → One model links to exactly one other model.
hasOne()&belongsTo()→ Define the relationship in models.- Eager Loading (
with()) → Optimizes database queries. - 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! 👇
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.