Laravel 9. PHP 8.0.
The task is to write an array line by line. Can you tell me why writing with eloquent in this form does not work, while writing as DB select works fine. What is my problem?
Original code
$task = $request['task'];
$datetask = $request['datetask'];
$timetask = $request['timetask'];
for ($i = 0; $i < count($task ); $i++) {
DB::insert('insert into tasks (task,datetask,timetask,)values(?,?,?)',
[$task[$i],$datetask[$i],$timetask[$i]]);
};
and Eloquent code:
for ($i = 0; $i < count($task); $i++) {
$task= new Task;
$task->task = $request['task'];
$task->datetask = $request['datetask'];
$task->timetask = $request['timetask'];
$task->save();
}
Error:
Array to string conversion.
Line:: $task->save();
3
Answers
You are getting array to string conversion so you need to use loop with
[i]
for all 3 param valuesOr if you are passing array values directly, then don’t use loop
In Eloquent, you have missed to use the loop variable
$i
.In your original code you are passing variables with
[$i]
asYou need to use same variable
Or just use [$i] with your data.
If you want to insert multiple records without loop, try this.