Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dominiquevienne/58ec48bebd8111e270a303042ce2202e to your computer and use it in GitHub Desktop.
Save dominiquevienne/58ec48bebd8111e270a303042ce2202e to your computer and use it in GitHub Desktop.
One to One Laravel relation - HasOne / BelongsTo - Owner <-> Car
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOwnersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('owners', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('car_id);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('owners');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->string('license_plate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cars');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
use HasFactory;
protected $fillable = [
'licence_plate',
];
public function owner()
{
return $this->belongsTo(Owner::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Owner extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
public function car()
{
return $this->hasOne(Car::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment