Laravel 8 One to One Relationship Example

In this tutorial we learn Laravel 8 One to One Relationship Example. Also we explain one to one model relationship in laravel 6, laravel 7 and laravel 8 app, Example of CRUD with one to one relationship. I eaxplain One to One model relationship is very simple and basic. We will learn how we can create migration with foreign key.

In this example, I will create users table and addresses table. both table are connected with each other. Now we will create one to one relationship using laravel Eloquent Model.

Laravel 8 One to One Relationship Example

Create Migrations:

Now create migration of users table.

users table migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable 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');
    }
}

 

Read Also :  How to Send Bulk Mail in Laravel 8 Using Queue

Now create migration of addresses table. We will also add foreign key with users table.

addresses table migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string("name");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addresses');
    }
}

Create Models:

Here, We  create User and Address table model. We will use hasOne() and belongsTo() for relationship of both model.

Read Also :  Laravel 8 Image Upload Example

User Model:

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

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 arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function address(){
        return $this->hasOne(Address::class);
    }
}

Address Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    use HasFactory;

    protected $fillable = ['name'];
}

Create Route:

<?php

use Illuminate\Support\Facades\Route;
use App\Models\User;
use App\Models\Address;

// ============= Eloquent One to One Relationship CRUD ==================

Route::get("insert/{id}", function($id){
    $user = User::findOrFail($id);
    $address = new Address(["name" => "201 abc"]);
    $user->address()->save($address);
});

Route::get("update/{id}", function($id){
    $address = Address::where("user_id", $id)->first();
    $address->name = "210 xyz";
    $address->save();
});

Route::get("read/{id}", function($id){
    $user = User::find($id);
    return $user->address;
});

Route::get("delete/{id}", function($id){
    $user = User::find($id);
    $user->address->delete();
});

I hope you understand of Laravel one to one relationship…