Table of contents

In this tutorial, you will learn to implement the Laravel 8 one to one relationship. One-to-one model relation in Laravel is the basic relationship that we usually encounter when doing the Laravel project. If you're new to Laravel this tutorial is for you. I will show you an example that is easy to understand and may help you in your future projects on Laravel.
Â
In this example, we will use the users
table and user_contact_infos
table and these tables are connected which the user has a user contact info with the use of user_id
key inside user_contact_infos
table.
Â
To start we need to create first our tables for our one-to-one relationship using Laravel eloquent.
Â
Step 1: Create Migration
Since in default the Laravel installations have a users table already we will just skip it and run the migration for our user_contact_infos
table.
Â
Run the following command:
php artisan make:migration create_user_contact_infos_table
Â
Here is the complete code below:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUserContactInfosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user_contact_infos', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->string('city'); $table->string('phone'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('user_contact_infos'); } }
Â
For the sake of this tutorial I will show you also the code for users table migration:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable 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'); } }
Â
Step 2: Laravel One to One Models
Now let's set up our User.php
a model since it is already included in the installation we don't need to run a command:
Â
See below code:
<?php namespace App\Models; use App\Models\UserContactInfo; use Laravel\Sanctum\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * Get the phone record associated with the user. */ public function user_contact_info() { return $this->hasOne(UserContactInfo::class); } }
Â
As you can see above we added the user_contact_info()
method for hasOne()
which is the name of our related model class.
Â
Now let's create a UserContactInfo.php
model. Run the following command:
Â
php artisan make:model UserContactInfo
Â
Here is the complete code below of our UserContactInfo
model.
<?php namespace App\Models; use App\Models\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; class UserContactInfo extends Model { use HasFactory; /** * Get the user that owns the contact info. */ public function user() { return $this->belongsTo(User::class); } }
Â
As you can see we added user()
a method with belongsTo()
method. It will automatically attempt to find a User model that has an id that matches the user_id column on the UserContactInfo
model.
Â
Now we have already set up our Laravel one-to-one relationship models. Let's try to create some data for this.
Â
Step 3: Create Data on Laravel One to One Relationship
In this section, we will create users with user contact info to test our Laravel one-to-one relationship.
Â
Creating user's record.
// Create User $user = new User; $user->name = 'Juan Dela Cruz'; $user->email = 'juan@gmail.com'; $user->password = bcrypt('password'); $user->save(); $user = new User; $user->name = 'Juana Santa Cruz'; $user->email = 'juana@gmail.com'; $user->password = bcrypt('password'); $user->save();
Â
Creating user contact info.
$user = User::find(1); $userContactInfo = new UserContactInfo; $userContactInfo->city = 'Bayawan City'; $userContactInfo->phone = '09261234567'; $user->user_contact_info()->save($userContactInfo);
Â
If you have the same user contact info and want to use it by the other user then the code below will be applied.
$userContactInfo = UserContactInfo::find(1); $user = User::find(2); $userContactInfo->user()->associate($user)->save();
Â
Step 4: Retrieve Laravel One to One Relationship
Now let's retrieve the records using Laravel one-to-one relationship. See the below example.
$userContactInfo = User::find(1)->user_contact_info; dd($userContactInfo);
Â
That's it. I hope it helps. Thank you for reading :)
Read next