Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel + nullable foreign keys

Tags:

laravel

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?

like image 317
mpen Avatar asked May 03 '14 23:05

mpen


1 Answers

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;
}
like image 171
mpen Avatar answered Dec 20 '22 21:12

mpen