Monday, March 6, 2017

laravel backpack not updating json field

I have a TEXT Column in my MySQL Table, which I want to fill with a JSON Object as String so I can define some options for the entry I am saving per row.

I only have one option yet, so I show only one checkbox, with a value of 1. Now when the form is submitted, I validate the input via the request. To make shure that there is always a value available I check if the input exists (remember its a checkbox) and if not, I prefill it with the option set to 0. But when I take a look at phpMyAdmin the old value remains.

Here the example by code - I was never good in explaining my self in englisch :P

Form

    <label for="dedication" style="font-weight: normal;"><input id="dedication" type="checkbox" name="fields[dedication]" value="1" />&nbsp;Dedication</label>

Request::all() overwrite

public function all() {

    // get input
    $input = parent::all();

    // save empty array if fields not set
    if (!isset($input['fields'])) {
        $input['fields'] = array("dedication" => "0");
    }

    $this->replace($input);

    // dd(parent::all());

    return parent::all();
}

Model

protected $table = 'products';
protected $primaryKey = 'id';
// public $timestamps = false;
protected $guarded = ['id'];
protected $fillable = ['product', 'description', 'price', 'campaign_id', 'quantity', 'fields'];
protected $hidden = ['created_at', 'updated_at'];
// protected $dates = [];
protected $casts = ['fields' => 'array'];

Example

Lets say I create a Product, and don't check the dedication checkbox, then the Product is saved with a value of NULL in the fields column. Wanted is {"dedication": "0"}.

When I now update this entry, and check the dedication checkbox, it works. Value is {"dedication": "1"}.

Now, if I update the entry again, and leafe the checkbox unchecked, the fields column is not overwritten so the old value remains.

The Question

How the hack can I update the values of this column? ^^

Thanks!



via Thomas Venturini

Advertisement