Laravel 11 One to One Eloquent Relationship Example

Laravel one to one eloquent relationship example; Through this tutorial, i am going to show you what is one to one eloquent relationship and how to use one to one eloquent relationship in laravel apps.

A one-to-one relationship is a very basic relation. In this guide, I’m going to explain one to one eloquent relationship model. I’ll show how to insert data and retrieve data using the eloquent model.

Laravel 11 One to One Eloquent Relationship Example

Use below given steps to create one to one relationship and also you can read, insert, update, delete (crud) data using this eloquent relationship in laravel apps:

  1. Install Laravel and Basic Configurations
  2. Create Migration and Model
  3. Setup One To One Relationship
  4. Inverse Of The Relationship
  5. Insert Records
  6. Retrieve Records
  7. Update Records
  8. Delete Records

Step 1 : Install Laravel and Basic Configurations

Run the following command on the command prompt to install or download Laravel app:

 composer create-project --prefer-dist laravel/laravel Blog

Step 2 : Create Migration and Model

Run the following command on command prompt to create a model named Mobile with a migration file:

php artisan make:model Mobile -m

Now open the migration file for the Mobile model from database>migrations directory. Then paste the below code in the up() function of the migration file.create_mobiles_table.php

public function up()
{
    Schema::create('mobiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('mobile');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')
            ->onDelete('cascade');
    });
}

To set user_id as a foreign key and mobile number will be deleted if delete the user.

Step 3 : Setup One To One Relationship

To define this relationship between  mobile and User model. The mobile method should call the hasOne method and return its result.app/User.php

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    // ...

    /**
     * Get the mobile number associated with the user.
     */
    public function mobile()
    {
        return $this->hasOne(Mobile::class);
        // note: we can also inlcude Mobile model like: 'App\Mobile'
    }
}

Step 4 : Inverse Of The Relationship

To define the inverse of a hasOne relationship using the belongsTo method.

Open Mobile model and paste this code:app/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Mobile extends Model
{
    /**
     * Get the user that owns the mobile.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Step 5 : Insert Records

Let’s add data to user and mobile from controller:UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Mobile;
use Hash;

class UserController extends Controller
{
    public function addUserMobile()
    {
        $user = new User;
        $user->name = "Test Name";
        $user->email = "[email protected]";
        $user->password = Hash::make("12345678");
        $user->save();

        $mobile = new Mobile;
        $mobile->mobile = '123456789';
        $user->mobile()->save($mobile);
    }
}

Step 6 : Retrieve Records

To fetch data from relationship model; as follows:

public function index()
{
    // get user and mobile data from User model
    $user = User::find(1);
    var_dump($user->name);
    var_dump($user->mobile->mobile);

    // get user data from Mobile model
    $user = Mobile::find(1)->user;
    dd($user);

    // get mobile number from User model
    $mobile = User::find(1)->mobile;
    dd($mobile);
}

Copy

Step 7: Update Records

To update data in model; as follows:

public function update()
{
    $user = User::find(1);

    $user->name = 'Test II';
    $user->mobile->mobile = '987654321';
    $user->push();
}

Copy

Step 8 : Delete Records

To delete data from both table; use the following method:

public function delete()
{
    $user = User::find(1);
    $user->delete();
}

 To get more details of one to one eloquent relationship, you can read Laravel’s official documentation.

Leave a Comment