Home > Net >  How to store an object in the Laravel database
How to store an object in the Laravel database

Time:09-21

I have a list of menus as follows When I move the menus using the Nestable library, an object is sent to the backend as shown below. How can I save it in the database?

Data Base

[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]

Menu List

CodePudding user response:

You could save it as a JSON in database

for example in your migration

$table->json('YOUR-COLUMN-NAME')->nullable();

and in your model

    protected $casts = [
        'YOUR-COLUMN-NAME' => 'array',
]

CodePudding user response:

just encode your array into json and save it into the table like

$data=json_encode([{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]);

$model->create(['data'=>$data]);

then you can retrive the data by decoding like

$obj=Model::first();
$data=json_decode($obj->data);

you can also check json_encode and json_decode for more details

CodePudding user response:

As written in the official documentation, Array & JSON Casting is what you need (to read more and see examples click here)

The array cast is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.

  • Related