I want to store some json format data in database from a given array. But How i do store it using controller.
Suppose I have json data like :
{\"id\"
You can convert your Model to JSON format like
$model->toJson();
or
if you have data in an array you can use json_encode(['id' => 1, 'name' => 'User 1']);
Laravel Schema does support JSON field types as well look https://laravel.com/docs/5.0/schema#adding-columns
You can use text
field type as well to store JSON data.
You don't need to convert the array data to a JSON string yourself, use the Laravel $casts parameter on your model: https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting
You should do something like this in your Div model:
protected $casts = [
'divisions' => 'array',
];
Set your model
protected $casts = [
'list' => 'array'
];
Here is the full code.
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'primary_id',
'list'
];
protected $casts = [
'list' => 'array'
];
public function setMetaAttribute($value)
{
$list = [];
foreach ($value as $array_item) {
if (!is_null($array_item['key'])) {
$list[] = $array_item;
}
}
$this->attributes['list'] = json_encode($list);
}