Use the creating
, updating
or saving
model events to loop trough your attributes
property to set fields to null
.
class Model extends \Eloquent {
public static function boot() {
parent::boot();
static::creating(function($model){
foreach ($model->attributes as $key => $value) {
$model->{$key} = empty($value) ? null : $value;
}
});
}
}
Thnx! Weird thing is that i still get: SQLSTATE[HY000]: General error: 1366 Incorrect decimal value: '' for column 'sending_cost_netherlands' at row 1
This is working fine:
public function setSendingCostNetherlandsAttribute($value)
{
if(empty($value)){
exit;
}
}
Solution for me:
public static function boot() {
parent::boot();
static::creating(function($model){
foreach ($model->attributes as $key => $value) {
$model->{$key} = empty($value) ? null : $value;
}
});
static::updating(function($model){
foreach ($model->attributes as $key => $value) {
$model->{$key} = empty($value) ? null : $value;
}
});
}
Use saving
if you are going to use it both for creating and updating. That way you only need one method instead of two.
I have only one strange thing with this piece of code:
public static function boot() {
parent::boot();
static::saving(function($model){
foreach ($model->attributes as $key => $value) {
if($value !== 0) {
$model->{$key} = empty($value) ? null : $value;
}
}
});
}
This piece of code getting called two times when saving a model:
public function setPaymentWaysAttribute($value)
{
if($value) {
$value = explode(',', $value);
$this->attributes['payment_ways'] = serialize($value);
} else {
$this->attributes['payment_ways'] = null;
}
}
So need to make again a fix for this field and also for checkboxes:
public static function boot() {
parent::boot();
static::saving(function($model){
foreach ($model->attributes as $key => $value) {
if($value !== 0 AND $key != 'payment_ways') {
$model->{$key} = empty($value) ? null : $value;
}
}
});
}
A lot of fixing things, for just setting empty fields in the database with the value NULL.
solution is changing #model->attributes with $model->toArray().
how about setting your mysql table's column default value to null, and making it nullable making it consistent
Nice - handy solution. I needed to make emails on a table unique (and so had a unique index) but also optional. This meant all empty emails had to be saved as a NULL rather than an empty string "". Handing it in the saving
event means that it makes no difference how or where the email is set, its mapping to a NULL is safeguarded at a low level in eloquent.
public function create(CarsRequest $request){
//array_filter setting empty field to null
$inputs = array_filter($request->all(), 'strlen');
Car::create($inputs);
$request->session()->flash('alert-success', 'Car created with success.');
return redirect()->action('CarController@index');
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community