skip to Main Content

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


  1. You are getting array to string conversion so you need to use loop with [i] for all 3 param values

    for ($i = 0; $i < count($request['task']); $i++) {
      $objTask= new Task; // don't use $task, which is already defined
      $objTask->task = $request['task'][$i]; // missing [$i] here
      $objTask->datetask = $request['datetask'][$i];
      $objTask->timetask = $request['timetask'][$i];
      $objTask->save();
    }
    

    Or if you are passing array values directly, then don’t use loop

      // for ($i = 0; $i < count($request['task']); $i++) {
      $objTask= new Task; // don't use $task, which is already defined
      $objTask->task = $request['task']; // passing request param directly
      $objTask->datetask = $request['datetask'];
      $objTask->timetask = $request['timetask'];
      $objTask->save();
      // }
    
    Login or Signup to reply.
  2. In Eloquent, you have missed to use the loop variable $i.
    In your original code you are passing variables with [$i] as

    DB::insert('insert into tasks (task,datetask,timetask,)values(?,?,?)',
                    [$task[$i],$datetask[$i],$timetask[$i]]);
    

    You need to use same variable

    for ($i = 0; $i < count($task); $i++) {
        $task= new Task;
        $task->task = $task[$i];
        $task->datetask = $datetask[$i];
        $task->timetask =$timetask[$i]];
        $task->save();
    }
    

    Or just use [$i] with your data.

     $objTask->task = $request['task'][$i];
     $objTask->datetask = $request['datetask'][$i];
     $objTask->timetask = $request['timetask'][$i];
    
    Login or Signup to reply.
  3. If you want to insert multiple records without loop, try this.

    //considering $task is muti record array.
    Task::insert($task);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search