Laravel 9 One To One Relationship Example

Schema::create('users', function (Blueprint $table) {    $table->increments('id');    $table->string('name');    $table->string('email')->unique();    $table->timestamps();});
Schema::create('phones', function (Blueprint $table) {    $table->increments('id');    $table->integer('user_id')->unsigned();    $table->string('phone_no');    $table->timestamps();        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');});
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class User extends Model
{
/**
* Get the phone associated with the user.
*/
public function phone()
{
return $this->hasOne(Phone::class);
}
}
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
public function user()
{
return $this->belongsTo(User::class, 'foreign_key');
}
$phone = User::find(1)->phone;$user = Phone::find(1)->user;
$user = User::find(1);

$phone = new Phone;
$phone->phone_no = '9876543210';

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

$user = User::find(1);

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

--

--

--

I am Laravel and PHP Developer. I have also Good Knowledge of JavaScript, jQuery, Bootstrap and REST API.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

TMWL February 20' — fzf, Datadog & Teraform

The Job of Class, Single Responsibility Principle, DRY Principle

Three key qualities of great developers

Questions To Ask When Interviewing Developers In 2021 — Part 1

Flatiron CLI Project and Related Struggles

Convert Yolov5 to CoreML. Also add a decode layer.

Getting used to Terminal

How to Configure AWS SFTP Server with AWS S3

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Websolutionstuff

Websolutionstuff

I am Laravel and PHP Developer. I have also Good Knowledge of JavaScript, jQuery, Bootstrap and REST API.

More from Medium

How to make a page with pagination in Laravel

Single Responsibility Principle and Laravel

Laravel MySQL index hints scope

Laravel with Packages | Laravel Firebase Push Notification Tutorial