Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Flex's avatar
Level 4

how to save array data in to Mysql database in laravel 5.6

I have dynamically changing forms to save data in to mysql DB. so, I hope save data in array based to two columns table like item_name and Item_value but I have not an idea how to prepare My controller to array based to this data. can you help me. some guide, example or tutorials......

0 likes
7 replies
BishoyWagih's avatar

i see you don't need two database columns if you will use an array to store form data

so, to insert an array into database field you can do the following

1 - in the model define a protected property that casts the variable to an array

protected $casts = ['item_name' => 'array'];

2 - in the controller pass the key value pairs to this field

 $data = [

'form_field_1'  => 'value',
     'form_field_1'  => 'value2',
];
Flex's avatar
Level 4

@BishoyWagih I need one table and two columns, because same form values different to others. so, I need save some item_name data and item_values

igaster's avatar

@Flex then you also need a third column to group them. Probably this would also be a Foreign Key to another table so that you can refer to them as a single entry model..

1 like
jlrdw's avatar

Are you saying you want to save

item_name and Item_value

In an array?

Why,

Just have a column item_name and a column Item_value and save normal.

igaster's avatar

Your question is very abstract, so I can not give a specific example. But the general idea is the same.

Example schema:

table: form_submits
- id
- other_form_data

table: form_values
- key
- value
- form_submit_id

So once you have set the relationships you can:

$formData = FormSubmit::with('formValues')->find($some_id);
foreach($formData->formValues as $entry){
   echo $entry->key . '=' .  $entry->value;
}
1 like

Please or to participate in this conversation.