One possible solution to flatten a JSON column on a model is to use accessors and mutators. Here's an example implementation:
class YourModel extends Model
{
protected $casts = [
'details' => 'array',
];
public function getAttribute($key)
{
if (array_key_exists($key, $this->details)) {
return $this->details[$key];
}
return parent::getAttribute($key);
}
public function setAttribute($key, $value)
{
if (array_key_exists($key, $this->details)) {
$this->details[$key] = $value;
} else {
parent::setAttribute($key, $value);
}
}
public function save(array $options = [])
{
$this->attributes['details'] = $this->details;
return parent::save($options);
}
}
In this solution, we define the details column as an array in the $casts property of the model. This ensures that Laravel will automatically serialize and deserialize the column as JSON.
We override the getAttribute and setAttribute methods to handle accessing and setting the flattened keys. If the key exists in the details array, we return or set the value accordingly. Otherwise, we fall back to the parent implementation.
In the save method, we update the details attribute with the modified array before saving the model.
With this implementation, you can access and set the flattened keys directly on the model instance, like $model->key. The changes will be reflected in the details column when saving the model.