Home » Laravel One To One Relationship Tutorial

Laravel One To One Relationship Tutorial

Last updated on December 30, 2020 by

In this tutorial, we will learn about the Laravel One To One relationship. The relationship of database tables is as much important as our real-life relationship.

Laravel developers should be thankful to Taylor Otwell for this beautiful creation of Eloquent Relationship which saves our lots of time. By using Eloquent Relationship we don’t need to create complex database queries with JOINS. Let’s now understand the One To One Relationship.

Laravel One To One Relationship

The One to One is a very basic type of database relationship. For example, let’s say a User model is associated with one Passport model. Check so simple definition written by ScratchCode below:

In a very simpler word, If one table’s one record is associated with another table’s one record then it’s called the One To One relationship. So simple right? Check the below screenshot for a better understanding.

Definition by the ScratchCode.io
one to one laravel relationship real life examples
Real Life One To One Relationship Examples

Hope you understood now the One To One relationship is. Let’s now jump on a real Laravel example step by step. Bear with us guys. We hope that you are not fed up with us. Finger crossed.

Example Of One To One Relationship

The hasOne() method is used to define the 1 to 1 relationship and on another model, we will use the belongsTo() method to define the inverse relationship.

So if User model has associated with a Passport model then a passport() method needs to add in User model with hasOne() method. Let’s see how to do it.

01 Create Migrations

The users table migration automatically created while Laravel installation so we just need to create the passport table migration. To do so run the following command:

php artisan make:migration create_passports_table

After running the above command a new migration file created in database/migrations folder.

Now, let’s open the passports table’s migration file and let’s connect it with users table by defining user id and foreign key.

Passport Migration

Schema::create('passports', function (Blueprint $table) {
    $table->id();
    $table->integer('user_id')->unsigned();
    $table->string('passport_number')->unique();
    $table->timestamps();

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

After that run the php artisan migrate command creates tables into the database and then adds some dummy data by using a factory or with the help of a tinker.

02 Create Models

The User model automatically created while Laravel installation. So we just need to create the Passport model. To do so run the following command:

php artisan make:model Passport

After running the above command a new model file created in app/Models directory. If you are using an older version than Laravel 8 then it will be created in app/ directory.

Now, open the Passport and User model and define the relationship as below:

app/Models/User.php

<?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',
    ];


    /**
     * One to one relationship with User & Passport
     * ScratchCode.io
     * @var array
     */
    public function passport()
    {
        return $this->hasOne(Passport::class);
    }
}

app/Models/Passport.php

<?php

namespace App\Models;

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

class Passport extends Model
{
    use HasFactory;

    /**
     * One to one relationship with User & Passport
     * ScratchCode.io
     * @var array
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

03 Read Records

Let’s quickly read the records using tinker console. Run the following command to open the tinker console:

php artisan tinker

After running the above command you will be entered into the tinker shell. Let’s check fetch the passport data associated with any user.

App\Models\User::find(41)->passport
read data with laravel relationship
Reading data with Laravel relationship using Tinker

Same way read the data using Passport model to retrieve the user.

App\Models\Passport::find(1)->user
read data with laravel inverse relationship
Reading data with Laravel inverse relationship using Tinker

04 Create Records

Write following code in any Controller to create records with relationship.

$user = User::find(1);
$passport = new Passport;

$passport->passport_number = 'AB124HERKHKBSD78646DFJ';
$user->passport()->save($passport);
$passport = Passport::find(1);
$user = User::find(10);

$passport->user()->associate($user)->save();

Additionally, read our guide:

  1. Laravel One To Many Relationship Tutorial With Example
  2. Best Way to Remove Public from URL in Laravel
  3. Error After php artisan config:cache In Laravel
  4. Specified Key Was Too Long Error In Laravel
  5. AJAX PHP Post Request With Example
  6. How To Use The Laravel Soft Delete
  7. How To Add Laravel Next Prev Pagination
  8. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  9. Difference Between Factory And Seeders In Laravel
  10. Laravel: Increase Quantity If Product Already Exists In Cart
  11. How To Calculate Age From Birthdate
  12. How to Convert Base64 to Image in PHP
  13. Check If A String Contains A Specific Word In PHP
  14. How To Find Duplicate Records in Database
  15. How To Convert Word To PDF In Laravel

That’s it for now. We hope this article helped you to learn Laravel One To One Relationship.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment

*

code