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 can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database. This article describes the options for storing JSON documents in SQL Server or SQL Database.
MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.
MongoDB. MongoDB is the most popular NoSQL database. A free and open source, cross-platform, document-oriented database, MongoDB uses JSON-like documents with schemas.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With