Laravel Eloquent One to One Relationship Tutorial with Example

Last modified on June 5, 2020 2 min read

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.

In this tutorial, I’ll create two tables called users and mobile. Here’s the schema design:

Table of Contents

  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

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Step 2 : Create Migration and Model

We have already the User model and migration file. Let’s create a model named Mobile with a migration file. Run this command to create both:

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

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

Step 3 : Setup One To One Relationship

We have two models User & Mobile. For example, a User model might be associated with one Mobile. To define this relationship, we place a mobile method on the User model. The mobile method should call the hasOne method and return its result.

app/User.php
<?php

namespace App;

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

So, we can access the Mobile model from our User. Now, let’s define a relationship on the Mobile model that will let us access the User that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method.

Open Mobile model and paste this code:

app/User.php
<?php

namespace App;

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\User;
use App\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

We can easily get data from relation model like this:

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

Step 7: Update Records

Let’s update the user’s table data and mobile’s table data at once:

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

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

Step 8 : Delete Records

We can easily delete both table’s data at once. Here’s the example:

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.

The tutorial is over. Thanks for reading. ๐Ÿ™‚

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

10 Replies to “Laravel Eloquent One to One Relationship Tutorial with Example”

  1. why there is two coloumn id and user_id in mobiles table in one to one relationship? Isnt it one to many relationship? there should be only id in mobile table where id is primary key as well as foriegn key

    1. Hi Amrit Shrestha,

      1. Yeah, your thinking is right. But I assumed that one user can have only one mobile number. If you assume one user can have multiple mobile numbers, then it’ll be “one-to-many relationship”.

      2. You can use only id in mobile table as the primary and foreign key.

      Thank you. ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *