Yajra Datatables - Column Date Format

5.9k views Asked by At

laravel 8 with yajra Datatables. The datatable is created well, but i need to custom some column data.

return [
            Column::computed('action')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->addClass('text-center'),
            Column::make('id')
                ->title('ID'),
            Column::make('name')
                ->title('Nome Acabamento'),
            Column::make('enabled')
                ->title('Visível'),
            Column::make('created_at'),
            Column::make('updated_at'),
        ];

In this example i need the created_at to be date format (d-m-Y) and id to be a sum operation from id + 1000.

4

There are 4 answers

1
Pirex360 On BEST ANSWER

I got it :

->editColumn('created_at', function($data){ $formatedDate = Carbon::createFromFormat('Y-m-d H:i:s', $data->created_at)->format('d-m-Y'); return $formatedDate; })

0
NOURDDINE BENYAHYA On

if you are using mysql and laravel 10 ,you can change format by mysql request

for example im working with document table and created_at column :

        ->addColumn('created_at_formatted', function ($document) {
            // Format the created_at column using MySQL date_format
            return $document->created_at->format('Y-m-d H:i:s'); 
            // Change the format as needed
        })

then add the column into your datatable

protected function getColumns()
{
    return [
        ['data' => 'created_at_formatted', 'name' => 'created_at_formatted', 'title' => 'Date'], // Add this line
    ];
}
1
Marvel C On
For example case : 

->editColumn('end_date', function($model){
            $formatDate = date('d-m-Y',strtotime($model->end_date));
            return $formatDate;
        })
->addColumn('legal','{{$model->legals->name}}')
->rawColumns(['action'])
->toJson();
1
nawt12 On

In Laravel 10, we use the following code for dataTables10.

 ->editColumn('created_at', function (Outcome $outcome) {
            return \Carbon\Carbon::parse($outcome->created_at )->isoFormat('DD.MM.YYYY');
        })