AppDividend
Latest Code Tutorials

Laravel One to One Relationship: Complete Guide

Laravel is famously known as an Eloquent ORM, which is Object-Relational Mapper. This tutorial will see how the One To One Relationship in Laravel is working with an example. So come along with me.

Prerequisites

If you are new to Laravel Eloquent Relationships, check out my Laravel Eloquent Relationships article in this blog.

Laravel One to One Relationship

A one-to-one relationship in Laravel is a fundamental relation. For example, the User model has only one Bank Account, so he has one account number. So we can connect both models, User, and Bank, as a one-to-one relationship with each other. We can place the account method into the User model class, and that account belongs to only one User. So in the User model, we can call the account method and that one call hasOne method.

Example

We are defining the one-to-one relationship with Bank and User. So first, we need to set their schema.

Step 1: Make one schema for account details.

Go to the terminal and type the following command.

php artisan make:migration create_accounts_table

So, it will create one schema file in which we need to define the columns like the following.

<?php

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

class CreateAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('account_number');
            $table->timestamps();
        });
    }

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

Now, fire the following command in the terminal.

php artisan migrate

It will create the tables in the MySQL database.

Step 2: Fill the tables with the values.

We need to fill two tables.

  1. users
  2. accounts

Type the following two commands in your terminal.

php artisan make:seeder UsersTableSeeder
php artisan make:seeder AccountsTableSeeder

Next, we need to input some random values. So in UserTableSeeder.php, type the following code.

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
          DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
           DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
            DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
             DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Okay, for the AccountsTableSeeder.php file, type the following command.

<?php

use Illuminate\Database\Seeder;

class AccountsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
    	DB::table('accounts')->insert([
		    'user_id' => 1,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 2,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 3,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 4,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 5,
		    'account_number' => rand(100000000,999999999)
        ]);
    }
}

Now, add the following code in the DatabaseSeeder.php file.

/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(AccountsTableSeeder::class);
    }

Type the following cmd in your terminal.

php artisan db:seed

Tables are filled with the values.

Step 3: Define a one-to-one relationship.

Make one model called Account.php by typing this command.

php artisan make:model Account

In the User.php file, write the following function to define the relationship with the Account model.

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

If we want to interact with the database, we need Laravel to provide one command-line interface called tinker. To boot up, the tinker hit the following command.

php artisan tinker

Now, type the following in the tinker.

$account = User::find(1)->account;

It will display the account details concerning user 1. So one to one relationship. One user has only one single account. Eloquent determines a foreign key of a relationship based on a model name.

In this case, the Account model is automatically assumed to have the user_id foreign key. If you wish to override this convention, you can pass the second argument to the hasOne method.

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

An Inverse Of The Relationship.

So, we can access an Account model from the User. Now, let’s define a relationship on an Account model that will allow us to obtain a User that owns an account. We can determine the inverse of the hasOne relationship using the belongsTo method.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    public function user()
    {
    	return $this->belongsTo('App\User');
    }
}

Eloquent will try to match a user_id from an Account model to an id on the User model in the example above. An Eloquent ORM determines a default foreign key name by examining the name of a relationship method and suffixing the method name with _id. However, if a foreign key on the Account model is not a user_id, you may pass the custom key name as the second argument to a belongsTo method.

Finally, our tutorial on Laravel One To One Relationship is over.

1 Comment
  1. abc says

    belongsTo

Leave A Reply

Your email address will not be published.

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