Laravel 8 HasOne() Example
Tags: laravel, tutorial, beginners, php
Published: 2022-05-16 06:32:04

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](https://codeanddeploy.com/blog/laravel/laravel-one-to-one-eloquent-relationship-tutorial-and-example) 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
php artisan make:migration create_user_contact_infos_table
```

Here is the complete code below:


```php
<?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');
    }
}
```
Now we have our migration already. Let's run the command below to migrate it.


```php
php artisan migrate
```

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
php artisan make:model UserContactInfo
```

Here is the complete code below of our UserContactInfo model.

```php
<?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);
    }
}
```

Next, we will set up our User.php model. See below the complete code:


```php
<?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 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.

```php
// 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.

```php
$user = User::find(1);
 
$userContactInfo = new UserContactInfo;
$userContactInfo->city = 'Dumaguete 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.


```php
$userContactInfo = UserContactInfo::find(1);
 
$user = User::find(2);
	 
$userContactInfo->user()->associate($user)->save();
```
Retrieve Record Example:


```php
$userContactInfo = User::find(1)->user_contact_info;
dd($userContactInfo);
```

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 :)