Scenario:
You have a User model. Each user has exactly one Profile. The Profile contains extra information like bio and phone_number.
Step 1: Create Models and Migrations
-
User model (already exists if you did
php artisan make:author default Laravel install) -
Profile model:
php artisan make:model Profile -m
public function up(): void
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->unique(); // one-to-one
$table->string('bio')->nullable();
$table->string('phone_number')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Run the migration :: php artisan migrate
Step 2: Define One-to-One Relationship
User model (app/Models/User.php):
public function profile()
{
return $this->hasOne(Profile::class);
}
Profile model (app/Models/Profile.php):
public function user()
{
return $this->belongsTo(User::class);
}
Now we are going to make a controller and display it in the view..
Step 1: Make a Controller
Run this command:
php artisan make:controller UserController
Step 2: Add a Method
Open UserController.php and add this
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
// Get all users with their profile in one query
$users = User::with('profile')->get();
return view('users.index', compact('users'));
}
}
Step 3: Add a Route
Open routes/web.php and add:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Step 4: Create the Blade View
Make a new file:resources/views/users/index.blade.php
Put this inside:
<!DOCTYPE html>
<html>
<head>
<title>Users & Profiles</title>
</head>
<body>
<h1>Users and their Profiles</h1>
<ul>
@foreach($users as $user)
<li>
<strong>{{ $user->name }}</strong>
@if($user->profile)
- {{ $user->profile->bio }} ({{ $user->profile->phone_number }})
@else
- No profile yet
@endif
</li>
@endforeach
</ul>
</body>
</html>
Step 5: Test it
-
Start your server:
http://127.0.0.1:8000/users
