I've got a form with a dropdown selection that lets you choose a foreign key for a particular model. The top option is always something like
<option value="">please select</option>
So when I fill my model with this data from the form,
$booking = new Booking($data);
And try to save it,
$booking->save();
It always fails because that violates the FK constraint because Laravel isn't smart enough to nullify this field for me. Thus 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 FKs and should be set to null if they an integer > 0?
One possible solution is to use set mutators for all your foreign keys:
public function setVehicleIdAttribute($value) {
$this->attributes['vehicle_id'] = $value ?: null;
}
public function setDriverIdAttribute($value) {
$this->attributes['driver_id'] = $value ?: null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With