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?


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

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.

链接地址: http://www.djcxy.com/p/92268.html

上一篇: 清除applicationIconBadgeNumber而不删除通知不起作用

下一篇: Laravel:如何将json格式数据存储在数据库中?