Laravel One to One Relationship

 Laravel One to One Relationship

 

  • Create Migrations :-

    users table migration 

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

    phones table migration

    Schema::create('phones', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('phone');
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')
        ->onDelete('cascade');
    });

  • Create Model :-

    User Model

    <?php

        namespace App;

        use Illuminate\Notifications\Notifiable;
        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',
    ];

    /**
    * Get the phone record associated with the user.
    */
    public function phone()
    {
    return $this->hasOne('App\Phone');
    }
    }

    Phone Model

    <?php

        namespace App;

        use Illuminate\Database\Eloquent\Model;

        class Phone extends Model
        {
        /**
        * Get the user that owns the phone.
      */
         public function user()
        {
        return $this->belongsTo('App\User');
         }
        }
        $phone = User::find(1)->phone;
        dd($phone);
        
        $user = Phone::find(1)->user;
        dd($user);
        $user = User::find(1);
        $phone = new Phone;
        $phone->phone = '8530393025';

        $user->phone()->save($phone);
        $phone = Phone::find(1);
        $user = User::find(10);

        $phone->user()->associate($user)->save();

That's it that's one to one relationship. Enjoy it....😊😀😀

Comments

  1. Very Useful and easy to learn blog.

    Keep it up brother.

    ReplyDelete
  2. Keep it up brother.

    ReplyDelete

Post a Comment

Popular Posts

Laravel Hidden Eloquent Memory Leak: Why Your App Crashes with Large Data

Laravel Performance Optimization: 15 Proven Tips to Make Your App Faster (2026)

Laravel vs Node.js: Which Is Better for Web Development in 2026?