Laravel 9 One To One Relationship Tutorial With Example

Hi guys,
Today, I am exaplian laravel 9 one to one relationship tutorial with example. One to One model relationship is very simple and basic. When one table refers to single row in another table that is called a one-to-one relationship. This tutorial will see how the One To One Relationship in Laravel 9 is working with an example.
Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 9 One to One Eloquent relationship as well as we will implement inverse of one to one relationship i.e belongs to.
So let's start following example:
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. * * @return void */ public function up() { 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. * * @return void */ public function down() { 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() { 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() { Schema::dropIfExists('phones'); } };Create Models:
Here, we will create User and Phone table model. we will also use "hasOne()" and "belongsTo()" for relationship of both model.
app/Models/User.php<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, 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', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * 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() { return $this->hasOne(Phone::class); } }app/Models/Phone.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Phone extends Model { use HasFactory; /** * Get the user that owns the phone. * * Syntax: return $this->belongsTo(Phone::class, 'foreign_key', 'owner_key'); * * Example: return $this->belongsTo(Phone::class, 'user_id', 'id'); */ public function user() { 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::find(1); $phone = new Phone; $phone->phone = '9429343852'; $user->phone()->save($phone); } }
<?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...
Divyang Vadodariya
My name is Divyang Vadodariya. I'm a full-stack developer, entrepreneur and owner of RvSolutionStuff. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap ,etc from the early stage.

We are Recommending you
- Laravel 8 Create Unique Slug Tutorial Example
- How To Custom Auth Register Method In Laravel 8?
- Send Mail Using Gmail SMTP Server Laravel 8 Example.
- Laravel 8 Refresh Datatable Without Reloading Page
- Laravel 9 Signature Pad Tutorial Example
- Laravel 9 Create Global Functions Tutorial
- Laravel 9 Create PDF File using DomPDF Example
- Laravel 9 Guzzle Http Request Example
- Laravel Validation For Multiple Files In Array
- Laravel 9 One To One Relationship Tutorial With Example
Copyright © 2023 www.RVSolutionStuff.com • All Rights Reserved