Laravel 6 – ONE TO ONE Eloquent Relationship With Example

one-to-one-relationship

Hello Friends, In this tutorial, i will show you what is one to one eloquent relationship and how we can use it in our code.

Best suitable example for one to one relationship is user and its passport. One user has one passport and same passport can not belongs to another user.

Lets start installing fresh laravel project using below command.

composer create-project --prefer-dist laravel/laravel one-to-one

Now update database credentials in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=one-to-one
DB_USERNAME=root
DB_PASSWORD=

Now run default migrations using below command. In default migration, Laravel comes with user migration and model. You can check them under database/migrations directory. While running php artisan migrate command laravel creates database tables from migrations.

php artisan migrate

You have successfully installed laravel and you can check it by enabling server using below command.

php artisan serve

Now navigate http://127.0.0.1:8000 in your browser. You will see laravel welcome page.

Create Passport Model And Migration

We already have default user table and model, so we will use it. We only need to make passport migration.

Lets make passport model and migration using below command.

php artisan make:model Passport -m

Above command will generate Passport.php model under app/ directory and TIMESTAMP_create_passports_table.php migration file under database/migrations directory.

Lets open passport migration files and add some field related to passport.

TIMESTAMP_create_passports_table.php

<?php

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

class CreatePassportsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('passports', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('passport_no');
            $table->string('place_of_issue');
            $table->date('date_of_issue');
            $table->date('date_of_expiry');
            $table->timestamps();
        });
    }

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

Also lets add passport migration fields in passport model $fillable property.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Passport extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'passport_no', 'place_of_issue', 'date_of_issue', 'date_of_expiry'
    ];

    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Implement Relationship Between User And Passport

To implement one to one eloquent relationship between user and passport, we need to place passport method into user model. The passport method should call the hasOne method and return its result.

Related:  Move laravel eloquent model into Models directory [Step By Step]

By using one to one relationship, we can access passport data from user model. I will show you next how to retrieve relationship data.

User.php

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

    // --- OTHER CODE

    public function passport()
    {
        return $this->hasOne('App\Passport');
    }
}

IMPORTANT

 

Here hasOne method takes three arguments shown as below.

 

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

 

The first argument passed to the hasOne method is the name of the related model. The second argument is foreign_key (Here user_id in passports table) and third argument is local_key (Here id in users table).

 

If you are using different column names rather than following conventional names, then you need to specify all arguments in hasOne method. Its good to follow conventional names to avoid mistakes.

Access/Retrieve Passport Data On User

You can access passport data by user as shown below.

$users = User::with('passport')->get();   // For Bulk User

$user = User::with('passport')->find('user_id');  // For Single User

Define Inverse Relationship

In the above relationship type, we have seen that we can use passport data from user model, but if we want user data based on passport than we need to add inverse relationship in passport model.

Lets see how to define inverse relationship.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Passport extends Model
{
    
    // -- OTHER CODE

    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

IMPORTANT

 

Here belongsTo method takes three arguments shown as below.

 

return $this->belongsTo('Related Model Class', 'foreign_key', 'local_key');

 

The first argument passed to the belongsTo method is the name of the related model. The second argument is foreign_key (Here user_id in passports table) and third argument is local_key (Here id in users table).

 

If you are using different column names rather than following conventional names, then you need to specify all arguments in belongsTo method. Its good to follow conventional names to avoid mistakes.

Retrieve Inverse Relationship Data

We can retrieve user data based on passport as shown below.

$passports = Passport::with('user')->get();     // For Bulk User

$passport = Passport::with('user')->find('passport_id');    // For Single User

Final Words

I hope that you understand about one to one eloquent relationship in laravel using above example. Share with your friends if you like this tutorial. Let me know question about this tutorial in the comment section.

About Chintan Panchal

I am web developer having 6+ year of experience of web development. Currently working on laravel and have worked on codeigniter, cakephp, symfony. Thank you :)

View all posts by Chintan Panchal →

One Comment on “Laravel 6 – ONE TO ONE Eloquent Relationship With Example”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.