Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
Hola Avatar asked Jun 14 '16 04:06

Hola


People also ask

Can you store JSON in a database?

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.

Does MySQL support Jsonb?

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.

What is the best database to store JSON?

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.


2 Answers

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',
];
like image 196
delatbabel Avatar answered Sep 20 '22 05:09

delatbabel


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.

like image 30
bbdangar Avatar answered Sep 24 '22 05:09

bbdangar