Hola
Hola

Reputation: 2233

Laravel : How to store json format data in database?

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?

Upvotes: 23

Views: 68968

Answers (3)

Jahirul Islam Mamun
Jahirul Islam Mamun

Reputation: 717

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

Upvotes: 5

bbdangar
bbdangar

Reputation: 61

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.

Upvotes: 6

delatbabel
delatbabel

Reputation: 3681

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',
];

Upvotes: 32

Related Questions