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