22

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":"bangladesh","divisions":[{"name":"Barisal"},{"name":"Chittagong"},{"name":"Dhaka"},{"name":"Khulna"},{"name":"Rajshahi"},{"name":"Rangpur"},{"name":"Sylhet"}]}

So far as I know in controller using json format is like this as I'm not fully aware of it.

public function saveUser(Request $request)
{
    $div=new Div();
    $user->json = json_encode( array({"Date 1": {
        {"id":"bangladesh","divisions":[{"name":"Barisal"},{"name":"Chittagong"},{"name":"Dhaka"},{"name":"Khulna"},{"name":"Rajshahi"},{"name":"Rangpur"},{"name":"Sylhet"}]}   
    $div->save();    
    return redirect('getList');
}

How do i save it in mySQL only the list of divisions in Division Model using Laravel Controller?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Hola
  • 2,163
  • 8
  • 39
  • 87

3 Answers3

28

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',
];
delatbabel
  • 3,601
  • 24
  • 29
6

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.

bbdangar
  • 61
  • 1
  • 3
  • Confirmed, I just converted a ` – agm1984 Mar 21 '19 at 05:42
4

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);
    }