Home > Back-end >  Laravel - Export carbon null return current time
Laravel - Export carbon null return current time

Time:12-16

Hello i had an excel export for date and time checked_at which suppoused to be null, but when im using Carbon format it become like this :

enter image description here

And here is the data that not using Carbon format :

enter image description here

is there a way for the null value to not get the current date when i try to export the excel?, thank you!.

here is my export code in my export.php :

public function map($data): array
    {
        return [
// $data->traffic_viewed_date,
            Carbon::parse($data['traffic_viewed_date'])->format('d-m-Y h:i'),

CodePudding user response:

The simplest solution i can think of is

return [
    ...
    (!is_null($data['traffic_viewed_date'])) ? Carbon::parse($data['traffic_viewed_date'])->format('d-m-Y h:i') : null;
    ...
];

CodePudding user response:

As the API docs that parse will not return null. If you want to return null if the value passed to Carbon class needs to be NULL

You can use make method instead.

$thisWillReturnNull = Carbon::make(null); // returns null
$thisWillCarbonInstance = Carbon::make('2021-12-16 10:50:25'); // returns Carbon instance

CodePudding user response:

In your case what you need is make not parse see below:

public function map($data): array
  {
    $dataAsCarbon = Carbon::make($data['traffic_viewed_date']); // returns `null` when argument is `null`
    return [
      // $data->traffic_viewed_date,
      $dataAsCarbon ? $dataAsCarbon->format('d-m-Y h:i') : $dataCarbon,
  • Related