jeudi 3 décembre 2020

Exporting Laravel Model to Excel but with modification of created_at column to only date not datetime

i tried to modify a collection before returning it to be exported with maatwebsite Excel. The column i tried to modify is the created_date column (the default created_date of laravel) so that when exported to excel, i only get the date not datetime.

i tried:

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;

class InvoicesExport implements FromCollection
{
    public function collection()
    {
        $temp = Invoice::all();
        $len = count($temp);
        for($i=0;$i<$len;$i+=1){
            $temp[$i]->created_at = $temp[$i]->created_at->format('m/d/Y')
        }
        return $temp;
    }
}

in the controller:

public function export() 
{
    return Excel::download(new InvoicesExport, 'invoices.xlsx');
}

but, when exported, the result in the excel file is, for example: '07/26/2016T00:00:00.000000Z'

i noticed that the time become zero, and when i tried:

$temp[$i]->created_at = "some random string"

the laravel in webpage return error said that "some random string" cannot be parsed to datetime by Carbon Class constructor.

how can i make the exporting does not construct datetime with the string i give in the 'created_at' column, but just return the plain string instead? if let's say, i can't modify the database so i can't create extra column and extra column for this simple thing is too much, i think.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire