I have a function which communicates with external API, and would like it to pass in optional parameters as a Carbon
instance, however API wants a Y-m-d
format so I've done this:
protected function boostsAPIRequest($token, Carbon $dateFrom = null, Carbon $dateTo = null)
{
try {
$boosts = $this->httpGetRequest($token,
$this->apiURL . 'stats/api/v1.0/boosts' . '/?date_from=' . $dateFrom->format('Y-m-d') . '&date_to=' . $dateTo->format('Y-m-d'));
//session()->put('boosts', $boosts);
} catch (ClientException $e) {
$this->errorHandling($e);
}
return $boosts ?? null;
}
this gives me an error saying
Call to a member function format() on null
Is there a way to keep it empty if no parameter was passed in?
Instead of:
$dateFrom->format('Y-m-d') . '&date_to=' . $dateTo->format('Y-m-d')
use should use:
($dateFrom ? $dateFrom->format('Y-m-d') : '') . '&date_to=' . ($dateTo ? $dateTo->format('Y-m-d') : '')
this is because you cannot run format
method on non-object (null in this case)