A one-to-one relationship means one record in a table is associated with only one record in another table.

Real-World Examples

  • One User → One Profile
  • One Student → One ID Card
  • One Order → One Invoice
  • One Company → One Address

01.Database Design

Example: User & Profile

users table

id
name
email

profiles table

id
user_id
phone
address

📌 Rule
The foreign key is always placed in the related (child) table.

02. Create Models & Migrations

php artisan make:model User -m
php artisan make:model Profile -m

users migration

Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});

profiles migration

Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('phone')->nullable();
$table->text('address')->nullable();
$table->timestamps();
});

Run migrations:

php artisan migrate

03. Define Relationship in Models

User.php (Parent Model)

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

Profile.php (Child Model)

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

04. How Laravel Knows the Relationship

Laravel automatically assumes:

Item Value
Foreign key user_id
Local key id
Table name profiles

If you use custom names, you must define them manually.

05. Fetch Related Data

Get profile of a user

$user = User::find(1);
$profile = $user->profile;

Access profile fields

echo $user->profile->phone;

Get user from profile

$profile = Profile::find(1);
$profile->user;

06. Create One-to-One Data

Using relationship (Recommended)

$user = User::find(1);

$user->profile()->create([
'phone' => '0123456789',
'address' => 'Dhaka, Bangladesh'
]);

user_id auto-assigned

07. Update One-to-One Data

$user->profile->update([
'phone' => '0199999999'
]);

08. Delete One-to-One Data

$user->profile()->delete();

09. Eager Loading (Performance Optimization)

❌ Wrong way (N+1 problem)

$users = User::all();

foreach ($users as $user) {
$user->profile;
}

✅ Correct way

$users = User::with('profile')->get();

10. Custom Foreign Key Example

public function profile()
{
return $this->hasOne(Profile::class, 'user_ref', 'id');
}

11. One-to-One in Controller Example

class ProfileController extends Controller
{
public function show($id)
{
$user = User::with('profile')->findOrFail($id);
return response()->json($user);
}
}

12. Blade View Example

<h2>User Profile</h2>

<p>Name: {{ $user->name }}</p>
<p>Phone: {{ $user->profile->phone ?? 'N/A' }}</p>
<p>Address: {{ $user->profile->address ?? 'N/A' }}</p>

Categorized in:

Laravel,