How to Use One to One Relationship in Laravel 11?

11-Apr-2024

.

Admin

How to Use One to One Relationship in Laravel 11?

Hi, Dev

In this article, we'll delve into utilizing the one-to-one Eloquent relationship in Laravel 11 applications. We'll leverage the hasOne and belongsTo methods to establish this relationship. Let's dive in and explore how to implement this effectively.

The one-to-one model relationship is fundamental yet powerful in its simplicity. It hinges on ensuring that one of the tables contains a key referencing the ID of the other table. In this tutorial, we'll explore how to set up migrations with foreign key schemas, fetch records, insert new data, update existing records, and more.

For demonstration purposes, let's consider creating a "users" table and a "phones" table, both intricately linked. We'll establish one-to-one relationships between them using Laravel's Eloquent Model. Our journey will begin with crafting a migration followed by creating the corresponding model. We'll then delve into retrieving records and mastering the art of creating new ones. Additionally, you'll find the database table structure outlined below for reference. Let's get started!

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' => 'Admin',

'email' => 'admin4@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...

#Laravel 11