Empty string instead of null values Eloquent
I've looked for the answer to this myself, and the closest I can come up with is using Mutators (http://laravel.com/docs/eloquent#accessors-and-mutators).
The same problem was solved by adding a (magic!) Mutator method for the foreign key field in the model:
public function setHeaderImageIdAttribute($value)
{
$this->attributes['header_image_id'] = $value ?: null;
}
For a table with a lot of foreign keys, this can get kind of bulky, but it's the most "built-in" method I've found for handling this. The upside is that it's magic, so all you have to do is create the method and you're good to go.
UPDATE -- Laravel 5.4 and above
As of Laravel 5.4, the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class
middleware handles this when the request is received. In my example above, if the request contains an empty string value for 'header_image_id', this middleware automatically converts it to null
before I can assign it to my model.
Laravel 4
If it is necessary you could remove any empty string in an array by filtering.
$input = array_filter(Input::all(), 'strlen');
Then if you have something like array('a' => 'a', 'b' => '')
you will get: array('a' => 'a')
.
As far as I know, if a field is not specified in the array for mass-assignment, then Laravel Eloquent ORM will treat it like NULL
.
Laravel 5
$input = array_filter(Request::all(), 'strlen');
or
// If you inject the request.
$input = array_filter($request->all(), 'strlen');
Probably more generic solution:
class EloquentBaseModel extends Eloquent {
public static function boot()
{
parent::boot();
static::saving(function($model)
{
if (count($model->forcedNullFields) > 0) {
foreach ($model->toArray() as $fieldName => $fieldValue) {
if ( empty($fieldValue) && in_array($fieldName,$model->forcedNullFields)) {
$model->attributes[$fieldName] = null;
}
}
}
return true;
});
}
}
The model where you needs to sanitize empty form fields should extends this class, then you should fill $forcedNullFields array with field names that required to be NULL in case of empty form fields:
class SomeModel extends EloquentBaseModel {
protected $forcedNullFields = ['BirthDate','AnotherNullableField'];
}
And thats all, you should not repeat same code in mutators.