Laravel: How to store json format data in a database?

I want to save some json format data in a database from a given array. But how do I store it using the controller.

Suppose I have json data like:

{"id":"bangladesh","divisions":[{"name":"Barisal"},{"name":"Chittagong"},{"name":"Dhaka"},{"name":"Khulna"},{"name":"Rajshahi"},{"name":"Rangpur"},{"name":"Sylhet"}]} 

As far as I know in a controller using json format, it seems like I don't quite understand 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 to save it in mySQL only in the list of partitions in the unit model using Laravel Controller?

+6
source share
2 answers

You do not 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 similar in your div model:

 protected $casts = [ 'divisions' => 'array', ]; 
+4
source

You can convert your model to JSON format, for example $model->toJson();

or

If you have data in the array, you can use json_encode(['id' => 1, 'name' => 'User 1']);

Laravel Schema supports JSON field types, and also looks like https://laravel.com/docs/5.0/schema#adding-columns

You can use the text field type as well as for storing JSON data.

0
source

All Articles