Laravel + neutral foreign keys

I have a form with a drop-down list that allows you to select a foreign key for a specific model. The top option is always something like

<option value="">please select</option> 

So, when I populate my model with this form data,

 $booking = new Booking($data); 

And try to save him

 $booking->save(); 

It always fails because it violates the FK constraint, because Laravel is not smart enough to invalidate this field for me. So I came up with this little hack:

 public function save() { if(!$this->vehicle_id) $this->vehicle_id = null; if(!$this->driver_id) $this->driver_id = null; parent::save(); } 

But is there no way to tell Laravel which fields represent FK and should be set to null if they are integers> 0?

+6
source share
1 answer

One possible solution is to use install mutators for all of your foreign keys:

 public function setVehicleIdAttribute($value) { $this->attributes['vehicle_id'] = $value ?: null; } public function setDriverIdAttribute($value) { $this->attributes['driver_id'] = $value ?: null; } 
+14
source

All Articles