Reputation: 159
I want to insert multiple rows in database in laravel when is insert it shows an error like this
Array to string conversion (SQL: insert into `equipments` (`created_at`, `driver_id`, `price`, `product_id`) values (2019-04-11 12:48:43, 1, 12, 5), (2019-04-11 12:48:43, 1, 12, 5))
html form http://prntscr.com/najtv9
dd response http://prntscr.com/najst5
this is controller
$product_id = $request->product_id;
foreach($product_id as $k => $id)
{
$values[] = [
'driver_id' => $request->driver_id,
'product_id' => $request->product_id,
'price' => $request->price,
'created_at' => Carbon::now()
];
}
DB::table('equipments')->insert($values);
Upvotes: 0
Views: 5067
Reputation: 1389
In your code you're passing the price
as array 'price' => $request->price,
it supposed be passed with key
foreach ($product_id as $key => $id) {
$values[] = [
'price' => $request[$key]->price,
];
}
Upvotes: 0
Reputation: 18577
You are getting that error because,
$product_id = $request->product_id;
Above this is a string fetched from $request
object. You can not loop a string.
EDIT
$product_id = $request->product_id;
foreach ($product_id as $k => $id) {
$values[] = [
'driver_id' => $request->driver_id,
'product_id' => $id,
'price' => $request->price[$k],
'created_at' => Carbon::now(),
];
}
This should work. Once replace your code with mine and check.
Upvotes: 3
Reputation: 679
you can use query builder insert function, this is how you can do it.
$rows = [
['2019-04-11 12:48:43', 1, 12, 5],
['2019-04-11 12:48:43', 1, 12, 5]
];
DB::table('table')->insert(
$rows
);
Upvotes: 0