In my model, I have an attribute 'data'
saved as type json. When I access this attribute, I want to json_decode
it and create an attribute for each keys. This part work fine
protected $dataAttribute = array('uiSearch');
public function getDataAttribute($value)
{
$json = json_decode($value,true);
$object = new stdClass;
foreach($this->dataAttribute as $attribute)
{
$this->data->attributes[$attribute] = '';
$object->{$attribute} = '';
}
if($json)
{
foreach($json as $key => $data)
{
if(property_exists($object, $key))
{
$this->data->attributes[$key] = $data;
$object->{$key} = $data;
}
}
}
return $object;
}
I can now access it like this
$model->data->uiSearch
I want to be able to set value of each new attributes and when I save the model, its goes back into json.
public function setDataAttribute($value)
{
$json = array();
foreach($this->dataAttribute as $attribute)
{
$json[$attribute] = '';
}
foreach($value as $key => $data)
{
if(isset($json[$key]))
{
$json[$key] = $data;
}
}
$this->attributes['data'] = json_encode($json);
}
Not working
$model->data->uiSearch = "test";
I tried to override eloquent saving method
public static function boot()
{
if(_B2B && Auth::check() && !defined('_INSURANCE'))
{
parent::boot();
static::saving(function($post)
{
// My attribute is empty
Log::error(print_r($post->data,true));
});
}
}