Laravel 9 One to One Relationship Tutorial with Example

Laravel 9

Nicesnippets

24-03-2022


Laravel 9 One to One Relationship Tutorial with Example

Hi friends,

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:

Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Add 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:

database/migrations/2014_10_12_000000_create_Users_table.php

<?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 artisan make:migration create_phones_table

database/migrations/2014_10_12_000000_create_phones_table.php

<?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');

}

};

Add 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);

}

}

php artisan make:model Phone

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:

app/Http/Controllers/UserController.php

<?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);

}

}

app/Http/Controllers/UserController.php

<?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);

}

}

Add Records:

app/Http/Controllers/UserController.php

<?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);

}

}

app/Http/Controllers/UserController.php

<?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();

}

}

It will help you...