I am attaching the driver’s id into the vehicle's table. It is working perfectly but duplicating the driver
id, should not be saved into the vehicle's table because
vehiclesand
drivers` have a one-to-one relationship?
Vehicle model
public function driver():BelongsTo
{
return $this->belongsTo(Driver::class);
}
Driver model
public function vehicle():IlluminateDatabaseEloquentRelationsHasOne
{
return $this->hasOne(Vehicle::class);
}
Controller
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->vehicle->driver()->associate($this->driver);
$this->vehicle->save();
}
2
Answers
A one-to-one relationship mean that a vehicule can have only one driver but you can still have multiple vehicule with the same driver.
If you want to create only one vehicule per driver your query should take this into account by using firstOrCreate/updateOrCreate.
The first parameters will be the constraint to fetch the existing record.
You will end up with something like this:
You should use a middleware to check if there is already a record in the database then abort the process. You can also use a middleware for your jobs (documentation here).
And if you don’t want to use a middleware, you can use something like this: