How To Define One To One Relationship In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 05-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.

How To Define One To One Relationship In Laravel Framework

One to One relationship

One to One relationship links one row in a database table to one row in another database table. One to One relationship is a fundamental relation and very easy to use.

 

Creating Model and Migration

To implement the one to one relationship in Laravel, we need two models: User and Profile

php artisan make:model Profile -m


after execution of above code profile.php model will be created.Now implement as below code

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
protected $table = 'profiles';

protected $fillable = ['dob','facebook'];
}

public function user() { 

return $this->belongsTo(User::class);

 }

open 2020_09_04_043607_create_profiles_table.php in database\migration folder and implement code as below
 
<?php 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
    public function up()
    {
            Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->date('dob');
            $table->string('facebook');
            $table->timestamps();
            });
    }

        public function down()
        {
                Schema::dropIfExists('profiles');
        }
}


after creating both file  run below command to create the tables in database.

php artisan migrate
 

Now we make one to one relationship for user and profile so open user model file and add profile function as below

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}


Now we do inverse one to one relationship by adding user function in profile model .php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model; 
class Profile extends Model

 { 
    protected $table = 'profiles';
    protected $fillable = ['dob','facebook'];

 public function user() {

    return $this->belongsTo(User::class);

  }
}
 

Fetch a One To One Relationship after creating relation between two tables now we can call above function to fetch data

$user = User::find(1);
$userDob = $user->profile->dob;


Creating a One To One Relationship we can also create new record using one to one relationship

$profile = new Profile();
$profile->dob = '19-04-1999';


$user = User::find(1);
$user->profile()->save($profile);
 

Deleting a One To One Relationship deleting created record

$user = User::find(1);
$user->profile()->delete();

Related Post