One to One Relationship

Demo details:

In this demo we have 2 models (Owner and Car), and 2 tables (owners and cars).

Business Rules:

The Owner can own one Car.

The Car can be owned by one Owner.

Relations Diagram:

Relationship Details:

The Cars table should store the Owner ID.

Eloquent Models:

class Owner

{

public function car()

{

return $this->hasOne(Car::class);

}

} class Car

{

public function owner()

{

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

}

}

Database Migrations:

Schema::create('owners', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

}); Schema::create('cars', function (Blueprint $table) {

$table->increments('id');

$table->string('name'); $table->integer('owner_id')->unsigned()->index()->nullable();

$table->foreign('owner_id')->references('id')->on('owners');

});

Store Records:

// Create relation between Owner and Car. $owner->car()->save($car); // Create relation between Car and Owner. $car->owner()->associate($owner)->save();

Retrieve Records: