Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dominiquevienne/7247aa61c6225a4c7baa6864c31c780c to your computer and use it in GitHub Desktop.
Save dominiquevienne/7247aa61c6225a4c7baa6864c31c780c to your computer and use it in GitHub Desktop.
Laravel One to Many example with Insurance and Vehicles
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateInsurancesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('insurances', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('insurances');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class UpdateVehiclesAddInsurance extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('vehicles', function (Blueprint $table) {
$table->unsignedBigInteger('insurance_id')->after('brand')->index();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('vehicles', function (Blueprint $table) {
$table->removeColumn('insurance_id');
});
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Insurance extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function vehicles()
{
return $this->hasMany(Vehicle::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
use HasFactory;
protected $fillable = [
'vehicle_type',
'brand',
/** Everything you would need about a vehicle */
];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function license()
{
return $this->hasOne(License::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function insurance()
{
return $this->belongsTo(Insurance::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment