Search code examples
laravelphp-carbon

How can I add days to date exist in database in laravel?


Let's say I have a table with some date values saved like this:

2022-02-02 00:00:00

How can I increase said date after retrieving it from the database? For example:

$importantDates = User::where('has_date', true)->pluck('date');
$increase = 2;
$changedDates = [];
foreach($importantDates as $date)
    $changedDates[] = ...; // add two days to the date

if $date contains '2022-02-02' how can I store '2022-02-04' inside $changedDates instead?


Solution

  • If the date column is carbon object then

    $user = \App\User::find(1);
    $user->date = $user->date->addDays(1);
    $user->save();
    

    If the date column is not carbon object then

    $user = \App\User::find(1);
    $user->date = Carbon::parse($user->date)->addDays(2);
    $user->save();