Table of contents
In this post, I will share with you an example of how to use the Laravel 8, 9 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_info
s table since we will use the default users 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');
}
}
Â
Now we have our migration already. Let's run the command below to migrate it.
Â
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 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);
}
}
Â
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);
}
}
Â
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();
Â
Creating user contact info.
$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.
$userContactInfo = UserContactInfo::find(1);
$user = User::find(2);
$userContactInfo->user()->associate($user)->save();
Â
Retrieve Record Example:
$userContactInfo = User::find(1)->user_contact_info;
dd($userContactInfo);
Read next