How do I update multiple columns with their respective values in laravel?

Viewed 388

I have a database record that I would like to update base on certain conditions. This condition is: when the pay_day is reached, I want to send the user that owns that record an email and then update the pay_day column to another date in the future using the interval_day column on the users' table. interval_day is just a number selected by the user.

Below is an illustration:

$now = Carbon::now();

User::where('approved', true)
            ->where('pay_day', '<', $now)
            ->chunkById(1000, function($users){
                foreach ($users as $user) {

                    $interval = $user->interval;
                    $payDay = $now()->addDays($interval);

                    // update the user...
                    $user->update([
                        'pay_day' => $payDay,
                    ]);
                    // if the user was updated, send an email next...
                }
                
            });

Now, let's say I have 100 different users with different interval values. I want their respective values in their interval columns to be what would be updated to their pay_day column and NOT the same date for all 100 users.

But when I run the above query it didn't update, neither the pay_day nor send email to the respective users. When I dd($interval & $payDay) it returns nothing.

Please what am I doing wrong? I need your suggestions. Thanks for your time in advance.

2 Answers

use like this

$updates = ([
                    'pay_day' => $payDay,
                  //other columns
                ]);
$x = User::where('approved', true)
        ->where('pay_day', '<', $now)->->update($updates);
if($x){
//succeed case
}

Not sure if $payDay = $now()->addDays($interval); is a typo or you've actually done that in your code, but $now is a variable not a function. Additionally you need to tell the closure in your chunkById function to use $now:

\App\Models\User::where('approved', true)
    ->where('pay_day', '<', \Carbon\Carbon::today())
    ->chunkById(1000, function ($users) {
        $users->each(function ($user) {
            $success = $user->update([
                'pay_day' => \Carbon\Carbon::today()->addDays($user->interval)
            ]);
            if ($success) {
                // send email
            }
    });
});

The above finds all approved Users where their pay_day is before today then processes the results in chunks of 1000 and updates the pay_day for each of them to be today + the interval value.

Related