'How can I add days to date exist in database in laravel? [closed]
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 1:[1]
Hello you can use Carbon library for that:
$date = Carbon::now();
$dateInFuture = $date->addDays($numberOfDays);
Solution 2:[2]
let say you have a date created_at as timestamp in your table. you may achieve it by using mutators instead of doing it manually every time.
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->addDays(5);
}
This will automatically add 5 days to your created_at column whenever your fetch it.
if you don't want to modify that column then what you may do is; in your model class add following lines;
protected $appends = ['future'];
public function getFutureAttribute()
{
return Carbon::parse($this->attributes['created_at'])->addDays(5);
}
this will append future attribute to your model whenever you query them on eloquent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christophe Hubert |
| Solution 2 |
