Laravel 9 One to One Eloquent Relationship Tutorial

Share this Article
Reading Time: 10 minutes
2,138 Views

Laravel eloquent relationship is a very important feature which connects one or more tables in a chain. This is the substitute of joins in laravel.

Laravel provides these following relationships –

Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 9 One to One Eloquent relationship as well as we will implement inverse of one to one relationship i.e belongs to.

This article will give you the detailed concept of about implementation of one to one relationship in laravel.

For this tutorial we will consider a users table and a phones table. This means a single user has a single phone number.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

Successfully, we have created a database.

To connect, Open up .env file which will be at root of project.

 DB_CONNECTION=mysql
 DB_HOST=127.0.0.1
 DB_PORT=3306
 DB_DATABASE=laravel_app
 DB_USERNAME=root
 DB_PASSWORD=root

Successfully, we have connected database to application.

Create Migrations

We need two migration file. One is for Users table and other is for Phones table. By default when we install laravel we get migration for users table.

Migration files are those files which create table schema inside database.

We will find migration 2014_10_12_000000_create_users_table.php of users inside /database/migrations folder.

Open up the migration file, we should see this following code into it.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Open project in terminal and run this migration command to create migration for phones table.

$ php artisan make:migration CreatePhonesTable

It will create a file 2022_03_31_170942_create_phones_table.php at /database/migrations according to the timestamp value.

Open file and write this whole code into it.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users');
            $table->string('phone');
            $table->timestamps();
        });
    }

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

Run Migrations

Next, we need to create tables inside database.

$ php artisan migrate

This command will create tables inside database.

Create Model

We need to create few models inside application. By default User.php is available inside application setup.

Open User.php and update with this code.

<?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;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Phone;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Get the phone associated with the user.
     * 
     * Syntax: return $this->hasOne(Phone::class, 'foreign_key', 'local_key');
     *
     * Example: return $this->hasOne(Phone::class, 'user_id', 'id');        
     */
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}

hasOne() method is used to get associated phone number of user. This is one to one relationship where each user has been associated to specific mobile number.

Next, We will create model for phones table.

Run this command to create model –

$ php artisan make:model Phone

It will create Phone.php file inside /app/Models folder. Open file and write this code.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Phone extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = [
        'user_id',
        'phone'
    ];

    /**
     * Get the user that owns the phone.
     * 
     * Syntax: return $this->belongsTo(Phone::class, 'foreign_key', 'owner_key');
     *
     * Example: return $this->belongsTo(Phone::class, 'user_id', 'id');        
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

belongsTo() method is implementing inverse relationship of one to one relationship in laravel.

Create Seeder with One to One Relationship

Back to terminal and type these artisan commands.

Seeder for users table:

$ php artisan make:factory UserFactory --model=User

Seeder for phones table:

$ php artisan make:factory PhoneFactory --model=Phone

It will create two files, UserFactory.php and PhoneFactory.php inside /database/factories folder.

Open UserFactory.php file and write this code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => bcrypt("123456"), // password
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return static
     */
    public function unverified()
    {
        return $this->state(function (array $attributes) {
            return [
                'email_verified_at' => null,
            ];
        });
    }
}

Open PhoneFactory.php file and write this code.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Phone>
 */
class PhoneFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            "user_id" => \App\Models\User::factory()->create()->id,
            "phone" => $this->faker->phoneNumber
        ];
    }
}

Next,

We need to use the concept of tinker to generate fake data using One to One Eloquent relationship.

Open terminal and type

$ php artisan tinker

Inside tinker shell panel, run this command to seed dummy data into database table.

>>> App\Models\Phone::factory()->count(10)->create()

This command will seed data inside both users and phones table. In both tables we will have 10 number of records.

Above command is only to generate factory data for phones table but inside PhoneFactory we have the code to generate factory data for users table as well.

"user_id" => \App\Models\User::factory()->create()->id,

Controller Usage

Open any controller say DataController.php file from /app/Http/Controllers folder.

Here, we have created two methods in which we used model methods as a property.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Phone;

class DataController extends Controller
{
    public function getPhone($user_id)
    {
        // Passing user id into find()
        return User::find($user_id)->phone;
    }

    public function getUser($phone_id)
    {
        // Passing phone id into find()
        return Phone::find($phone_id)->user;
    }
}
  • User::find($user_id)->phone; It will find phone details value by user id. One to One
  • Phone::find($phone_id)->user; It will find user details by phone id. Inverse of One to One / Belongs To

Create Routes

Open web.php from /routes folder and add these routes into it.

//...

use App\Http\Controllers\DataController;

Route::get('get-phone/{id}', [DataController::class, 'getPhone']);
Route::get('get-user/{id}', [DataController::class, 'getUser']);

//...

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URLs

Get Phone details: http://127.0.0.1:8000/get-phone/1
Get User details: http://127.0.0.1:8000/get-user/1

We hope this article helped you to learn Laravel 9 One to One Eloquent Relationship Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5