I'm trying to build a scheduler in which an incremental day addition and subtraction method is required.
Here, I am simply trying to add a day to this variable (which is displayed to the user elsewhere) each time this function is executed via a button I set up that routes to a certain location. But, I keep getting this error
Call to a member function addDay() on integer
whenever I try to execute this. I am new to using the Carbon interface and looked through the documents, which led me to try parsing the function (worked when I had the same error with a string) but to no avail obviously. Any help is appreciated and/or a possible explanation of how this error is working really.
function addDay(){
$day = (int) Carbon::now()->format('j');
$day = $day->addDay();
}
Thanks in advance. If there is a better way to do this (adding days incrementally with the button/link), I would love to hear it. My logic seems flawed after working on the application the entire day.
You're casting the Carbon
date object into an integer
by using the (int)
in the first $day
variable. Therefor when you're trying to access the function addDay()
it's failing, because $day
is no longer a Carbon
object but an integer
.
$day = Carbon::now();
$day = $day->addDay()->format('j');
This should work, and if you need to cast it to an integer
for some reason, then do it like this.
$day = Carbon::now();
$day = (int) $day->addDay()->format('j');
This way you cast the integer
after you've added the day.
There is also a much cleaner approach to this syntax, which uses method chaining like so
$day = (int) Carbon::now()->addDay()->format('j');
As @Classified said but a cleaner approach would be to work with Carbon object first and then apply format on that.
Like this:
$dateObj = Carbon::now()->addDay(); $day = (int) $dateObj->format('j');
Cleaner approach and better readability.
You have to addDay
to Carbon instance not to the integer (the day) :
$dt = Carbon::create(2012, 1, 31, 0); // 2012-01-31 00:00:00
echo $dt->addDay(); // 2012-03-04 00:00:00
What is the desired returned value ?
$day = Carbon::now()->addDay();
return $day->dayOfWeek; //day of the week, 03/08/18 (now) returns 6 (INT)
return $day->format('j'); //day of the month, 03/08/18 (now) returns "4" (STRING)
return $day->day; //day of the month, 03/08/18 (now) returns 4 (INT)
return $day //Carbon object (at now() + 24h) that you can manipulate