Reputation: 184
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:
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.
Upvotes: 0
Views: 1843
Reputation: 1026
try this
$services = $request->except('_token');
foreach ($services['services_selects'] as $index => $value) {
DB::table('services')->insert(['service_id' => $value]);
}
Upvotes: 1
Reputation: 310
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.
Upvotes: 1
Reputation: 198
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 ]);
Upvotes: 0