Home > Software design >  How to save the json array data in database in laravel?
How to save the json array data in database in laravel?

Time:12-29

does anyone know how to store the data in this format ["123"] in PHPMyAdmin?

Now the data I store into the database is only the value which is 123. I want to store the data like this ["123"]. Does anyone know how to do this?

Here is my code:

Company::create([
   'companyID' =>  $people->people_id,
]);

CodePudding user response:

To store data the way you want to, you need to change the datatype for the column of the table to json. It can be done in your migration file like:

$table->json('column_name');

After migrating your table you have to add casting for the specific column in your model file. It can be done as:

protected $casts = [
   'column_name' => 'array',
];

Once you have done this, you can then store data as json in your database.

You can find more information about casting at Laravel Docs here.

https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting

CodePudding user response:

You can save text data in mysql table column. For this you should change your column type to text and follow the following code as reference.

You will have to change your array to json data and pass variable to create method as value. Remember that, for storing string value you will have to wrap value with quotations.

$data = json_encode([
    123, "124", 134.4, "450"
]);

Company::create([

    'companyID' => $data

]);
  • Related