skip to Main Content

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 vehiclesanddrivers` 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


  1. 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:

    $this->vehicle
        ->driver()
        ->firstOrCreate(
            ['driver_id' => $driverId],
            $this->driver->toArray()
        );
    
    Login or Signup to reply.
  2. 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:

    Vehicle::query()
        ->where('driver_id', $this->driver->id)
        ->doesntExistOr(function() {
            $this->vehicle->driver()->associate($this->driver);
            $this->vehicle->save();
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search