Search code examples
mysqllaraveldatabaselaravel-query-builder

Laravel mass update a date column by adding a value from other column of same row


I have a following MySQL table:

id days_remaining final_date
1 4 2023-10-01
2 10 2023-10-01

I'm trying to mass update the final_date column. The resulting value of this column is a fixed date value eg: 2023-10-10 plus the days_remaining added into it.

This is the resulting table:

id days_remaining final_date
1 4 2023-10-14
2 10 2023-10-20

What I was trying, but no success:

DB::table('my_table')
    ->update([
        'final_date' => Carbon::parse('2023-10-10')->addDays(DB::raw('days_remaining'))->toDateString()
    ]);

Solution

  • Well you can use DB Facade:

    DB::table('my_table')
        ->update([
            'final_date' => DB::raw('DATE_ADD("2023-10-10", INTERVAL `days_remaining` DAY)')
        ])
    

    Or Elequont:

    YourModel::update([
            'final_date' => DB::raw('DATE_ADD("2023-10-10", INTERVAL `days_remaining` DAY)')
        ])