Search code examples
phplaravellaravel-5eloquentlaravel-excel

Laravel Excel convert change date format


I'm trying to convert date with laravel excel, below is my code :

<?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,
        ];
    }
}

So I manage to convert the created_at and expiry_date field but for some reason my start-date isn't unable to be converted and i receive this error :

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

I've checked in my database its a date field.

the start_date and expiry_date are date field and created_at is timestamp

if i convert the excel on default the expiry_date and created_at :

2019-09-27 18:54:54

while the start_date lok like this :

2014-10-22


Solution

  • 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.