phplaraveleloquentorm

How to update a Laravel Eloquent data, calculating a date diff


I have this problem. I need to update all data from a Table, each time incoming batch finishes inserting.

What I have to do is: Incoming data has CreationDate, so I need to do a DIFF with current date, and calculate the group. From 1 to 7 for every 30 days.

For example, if the date diff is 45 days... this belongs to group 2.

I know i could use a foreach loop. But my question is: is there any other option to optimize this task?.

maybe with laravel mutator, or an scope?.

I tried adding this on the insert part

    $group = intval((Carbon::now()->diffInDays($CreatedDate) ?? 1) / 30) + 1;

which works!. But I need to do this for all the previous data as well, which is a lot.


Solution

  • use Carbon\Carbon;
    use Illuminate\Support\Facades\DB;
    
    // Option 1: Using Query Builder with raw SQL
    YourModel::query()
        ->update([
            'group' => DB::raw('FLOOR(DATEDIFF(NOW(), created_date) / 30) + 1')
        ]);
    
    // Option 2: Using chunk processing for better memory management
    YourModel::chunk(1000, function ($records) {
        foreach ($records as $record) {
            $group = intval(Carbon::now()->diffInDays($record->CreatedDate) / 30) + 1;
            $record->update(['group' => $group]);
        }
    });
    
    // Option 3: Using a custom scope in your model
    class YourModel extends Model 
    {
        public function scopeUpdateGroups($query)
        {
            return $query->update([
                'group' => DB::raw('FLOOR(DATEDIFF(CURRENT_DATE, created_date) / 30) + 1')
            ]);
        }
    }
    
    // Then use it:
    YourModel::updateGroups();
    

    Create an accessor/mutator in your model or use a scheduled command for regular updates. My vote is to create your model