DEV Community

Cover image for Laravel 8 HasOne() Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 HasOne() Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-hasone-example

In this post, I will share with you an example of how to use the Laravel 8 hasOne() method on the model relationships. In my previous tutorial, I shared how to implement the Laravel one-to-one relationship which is used to link between the record in two tables, where each record in each table only show once.

Laravel hasOne() method is really helpful when doing Laravel one-to-one relationship which is used to retrieve the related record using Eloquent's dynamic properties.

Let's create two tables that are connected to each other. Where the user's table has contact info.

Step 1: Create Migration for our Laravel hasOne() Testing

In this example, we will just create migration for our user_contact_infos table since we will use the default users 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

Now we have our migration already. Let's run the command below to migrate it.

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

I assume that users table is already included.

Next, let's apply the Laravel hasOne() method to our model.

Step 2: Apply Laravel hasOne() method

We will create first our 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

Next, we will set up our User.php model. See below the complete 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 we implemented the Laravel hasOne() method to our User.php model class inside the user_contact_info() method which is the name of our related model class.

Step 3: Let's Save Record using Laravel hasOne()

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 = 'Dumaguete 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

Retrieve Record 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-8-hasone-example if you want to download this code.

Happy coding :)

Top comments (0)