How to store multiple values in one column

I want to store multiple values which comes from select2 multiple values in my laravel project. It returns an array with all inputs contains service ids. I want to store each value into database in the service_id column. How can I do this? I am new to laravel, using laravel 5.8.

dd() output of request:

enter image description here

here is my code:

$services = array();
 $services = $request->except('_token');
 foreach ($services as $id=>$value) {
   DB::table('services')->insert(['service_id' => $value]);
 }

It gives this error: “Column not found: 1054 Unknown column ‘0’ in ‘field list’ (SQL: insert into services (0, 1) values (6, 9))”

how can I solve this? thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The problem is you are passing an array to service id.
In your case the key will be services_select and value is an array in your foreach loop.

Try this

$services = $request->except('_token');
foreach ($services['services_selects'] as $id => $value) {
  DB::table('services')->insert(['service_id' => $value]);
}

Hope this will help.

Method 2

try this
 $services = $request->except('_token');
 foreach ($services['services_selects'] as $index => $value) {
   DB::table('services')->insert(['service_id' => $value]);
 }

Method 3

That is not great approach but if you have to do it in one column just add the (,).
First create local variable to store all your data then insert to the table

     $services = array();
     $services = $request->except('_token');
     $var = "";
     foreach ($services as $id=>$value) {
       $var = $var .",".$value;
     }
     DB::table('services')->insert(['service_id' => $var ]);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x