Laravel : How to store json format data in database?

后端 未结 3 765
梦谈多话
梦谈多话 2020-12-29 09:17

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\"         


        
相关标签:
3条回答
  • 2020-12-29 09:30

    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.

    0 讨论(0)
  • 2020-12-29 09:32

    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',
    ];
    
    0 讨论(0)
  • 2020-12-29 09:43

    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);
        }
    
    0 讨论(0)
提交回复
热议问题