Laravel 12 One to One Relationship Example
This article will help you how to use one to one eloquent relationship in laravel 12 application. we will use hasOne and belongsto method for one to one relationship.
One to One model relationship is very simple and basic. You have to make sure that one of the tables has a key that references the id of the other table. We will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records, etc.
In this example, I will create a "users" table and the "phones" table. Both tables are connected with each other. Now we will create one-to-one relationships with each other by using the Laravel Eloquent Model. We will first create a database migration, then a model, retrieve records, and then learn how to create records too. So you can also see the database table structure below the screen.
One-to-One relationship will use "hasOne()" and "belongsTo()" for relation.
Create Migrations:
Now we have to create migration of "users" and "phones" table. we will also add foreign key with users table. so let's create like as below:
users table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
phones table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('phones', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users');
$table->string('phone');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('phones');
}
};
Create Models:
Here, we will create a User and Phone table model. We will also use "hasOne()" and "belongsTo()" for the relationship of both models.
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasOne;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/**
* Get the phone associated with the user.
*
* Syntax: return $this->hasOne(Phone::class, 'foreign_key', 'local_key');
*
* Example: return $this->hasOne(Phone::class, 'user_id', 'id');
*/
public function phone(): HasOne
{
return $this->hasOne(Phone::class);
}
}
app/Models/Phone.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Phone extends Model
{
use HasFactory;
/**
* Get the user that owns the phone.
*
* Syntax: return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
*
* Example: return $this->belongsTo(User::class, 'user_id', 'id');
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
Retrieve Records:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$phone = User::find(1)->phone;
dd($phone);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Phone;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$user = Phone::find(1)->user;
dd($user);
}
}
Create Records:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Phone;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$user = User::create([
'name' => 'Hardik',
'email' => 'hardik4@gmail.com',
'password' => '123456'
]);
$phone = new Phone;
$phone->phone = '9429343852';
$user->phone()->save($phone);
dd($user);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Phone;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$phone = Phone::find(1);
$user = User::find(10);
$phone->user()->associate($user)->save();
}
}
I hope you understand of one to one relationship...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Current Full URL in Laravel 12?
- Laravel 12 Resize Image Before Upload Example
- Laravel 12 Ajax CRUD Operation Tutorial
- Laravel 12 Create Custom Error Page Example
- Laravel 12 JQuery UI Ajax Autocomplete Search
- Laravel 12 Send Email using Queue Example
- Laravel 12 Multiple File Upload Example
- Laravel 12 Database Seeder Tutorial Example
- Laravel 12 Bootstrap Auth Scaffolding Tutorial
- Laravel 12 Form Validation Tutorial Example
- Laravel 12 REST API Authentication using Sanctum Tutorial
- Laravel 12 Generate PDF File using DomPDF Example
- Laravel 12 CRUD Application Example Tutorial