DEV Community

Cover image for Laravel One to One Eloquent Relationship Tutorial and Example
Code And Deploy
Code And Deploy

Posted on

Laravel One to One Eloquent Relationship Tutorial and Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-one-to-one-eloquent-relationship-tutorial-and-example

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
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Creating user contact info.

$user = User::find(1);

$userContactInfo = new UserContactInfo;
$userContactInfo->city = 'Bayawan City';
$userContactInfo->phone = '09261234567';

$user->user_contact_info()->save($userContactInfo);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-one-to-one-eloquent-relationship-tutorial-and-example if you want to download this code.

Happy coding :)

Top comments (0)