Table of Contents
Inside this article we will see the concept i.e Laravel 10 One to One Eloquent Relationship Tutorial. Article contains the classified information i.e What is One to One Relationship and How it works in laravel.
In Laravel, a one-to-one relationship is a type of relationship between two database tables, where one record in the first table (the “parent” table) is associated with one and only one record in the second table (the “child” table).
Learn More –
- What is CSRF Token and How To Use in Core PHP Tutorial
- Laravel 10 FullCalendar Ajax CRUD Tutorial Example
- Laravel 10 How To Add Google reCaptcha v3 Validation
- How To Call MySQL Stored Procedure in Laravel 10 Tutorial
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;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Create Migrations
To see a real analysis of One to One relationship. Let’s consider a case.
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 xxx_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 xxx_create_phones_table.php inside /database/migrations folder.
Open migration file and write this complete 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 & Add Relationships
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\Database\Eloquent\Relations\HasOne; 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. */ public function phone(): HasOne { 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.
Usage
$phone = User::find(1)->phone;
Defining The Inverse Of The Relationship
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\Relations\BelongsTo; 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. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } }
belongsTo() method is implementing inverse relationship of one to one relationship in laravel.
Usage
Phone::find($phone_id)->user;
Controller Usage
Open any controller say DataController.php file from /app/Http/Controllers folder.
Here, we have created two methods in which we use 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 10 One to One Eloquent Relationship Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
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.