Format Date Column in Infyom Datatable - Laravel
Leonel Elimpe
by Leonel Elimpe
1 min read

Tags

  • Laravel
  • PHP

I have the following datatable class generated by Infyom’s Laravel Generator:

<?php

namespace App\DataTables;

// ...

class RequestDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'requests.datatables_actions');
    }

    // ..

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'amount',
            'sender',
            'created_at'
        ];
    }

    // ..
}

And it renders like below:

I’d like the Created At column to instead display dates in this format: Sat, Jun 20, 2020 11:11 AM. here’s what I added to make it work:

<?php

namespace App\DataTables;

// ...

class RequestDataTable extends DataTable
{
    // ..
    
    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'requests.datatables_actions')
            /** @see https://datatables.yajrabox.com/eloquent/carbon */
            ->editColumn('created_at', function ($request) {
                return $request->created_at->toDayDateTimeString();
            });
    }

    // ..
}

Note that with Laravel, the created_at and updated_at date fields are automatically cast to Carbon instances, so I could simply call whatever carbon method I wanted on the created_at Carbon instance as above. I chose the toDayDateTimeString() method which formats dates as below.

There are a couple of other methods you can use to format dates for humans, check them out: Format Dates for Humans with Carbon in PHP.


Further reading