Ehsan Mousavi
Ehsan Mousavi

Reputation: 429

Loop in Laravel's schedule define

How can I loop through each row of a table and update them with different values in Laravel's schedule define? I tried this for testing purposes in Kernel class but had an error:

$schedule->call(function () {
    $posts= Post::get();
    for( $i = 0; $i < count( $posts); $i++ ) {
        $posts[ $i ]>update([ 'title' => $i ]);
    }
})->everyMinute();

Upvotes: 0

Views: 427

Answers (2)

Afraz Ahmad
Afraz Ahmad

Reputation: 5386

You need to do this.

   $schedule->call(function () {
      $posts= Post::all();
      foreach($posts as $post) {
          $post ->update([ 'title' => $i ]);
             }
   })->everyMinute();

Post.php should have title column fillable to update it through eloquent update method.

protected $fillable = ['title','other columns',...];

Upvotes: 1

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

You a have syntax error inside the loop:

$posts[ $i ]->update([ 'title' => $i ]);

Upvotes: 1

Related Questions