Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : How to add days to datetime field?

Tags:

php

laravel

How to add days to datetime field in Laravel?

For example,
there is a updated_at field in articles table:

$article = Article::find(1);
$updated_at=$article->updated_at;

I want to add 30 days to updated_at field.

In Carbon, it could be done like this:

$expired_at=Carbon::now()->addDays(30);

But how to do it in above example?

like image 998
zwl1619 Avatar asked Sep 30 '17 16:09

zwl1619


3 Answers

Since updated_at and created_at fields are automatically cast to an instance of Carbon you can just do:

$article = Article::find(1);
$article->updated_at->addDays(30);
// $article->save(); If you want to save it

Or if you want it in a separate variable:

$article = Article::find(1);
$updated_at = $article->updated_at;
$updated_at->addDays(30); // updated_at now has 30 days added to it
like image 144
DevK Avatar answered Sep 22 '22 07:09

DevK


you can use Carbon::parse

$article = Article::find(1);

$updated_at=Carbon::parse( $article->updated_at)->addDays(30);

Suppose if updated_at is 2017-09-30 22:43:47 then output will be 2017-10-30 22:43:47.000000

like image 26
Vision Coderz Avatar answered Sep 24 '22 07:09

Vision Coderz


Have you tried like this with raw php? If you want you can change your datetime format inside first parameter of date()

$updated_at=date('Y-m-d H:i:s', strtotime('+30 day', $article->updated_at));
like image 22
Always Sunny Avatar answered Sep 24 '22 07:09

Always Sunny