Laravel Excel convert change date format

Trying to convert date with laravel

<?php

namespace App\Exports;

use App\Project;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class ProjectExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithTitle, WithEvents, WithColumnFormatting
{
    public function collection()
    {
        return Project::with('developer_projects')->get();
    }

    // Select data from query and set its position
    public function map($project): array
    {
        return [
            $project->name,
            Date::dateTimeToExcel($project->created_at),
            Date::dateTimeToExcel($project->start_date),
            Date::dateTimeToExcel($project->expiry_date),
        ];
    }

    // Set Date Format
    public function columnFormats(): array
    {
        return [
            'E' => NumberFormat::FORMAT_DATE_DDMMYYYY,
            'F' => NumberFormat::FORMAT_DATE_DDMMYYYY,
            'G' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }
}

Manage to convert the created at and expiry date field but for some reason my start-date isn’t unable to be converted and receive this error :

Argument 1 passed to PhpOffice\PhpSpreadsheet\Shared\Date::dateTimeToExcel() must implement interface DateTimeInterface, string given

checked in database its a date field.

the start_date and expiry_date are date field and created_at is timestamp

if convert the excel on default the expiry_date and created_at :

Add the start_date to the $dates attribute in your Project model

class Project extends Model
{
    protected $dates = ['created_at', 'updated_at', 'expiry_date', 'start_date'];
}

If the attribute is in $dates, the field will be returned as an instance of Carbon and not a simple string, then Maatwebsites Excel will use it to get the right format.

Leave a Reply