user8872543
user8872543

Reputation:

Laravel datatable date format doesn't work

I'm using datatable to display data include postingdate column, I need to change the format of postingdate column, as I found some tutorials about this and used the code below put when run. I got error message and table doesn't appear.

The error message:

DataTables warning: table id=users-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Code:

$users = Checks::select(['details', 'postingdate', 'description', 'amount', 'type', 'slip', 'vendor_id', 'category_id']);

return Datatables::of($users)->editColumn('postingdate', function ($user) {
return $user->postingdate->format('d-m-Y')})->make(true);

Upvotes: 3

Views: 12372

Answers (3)

Francesco Taioli
Francesco Taioli

Reputation: 2876

To fix this problem, you need to return two field to the UI, one used for display and one for sorting.

Controller

return Datatables::of(User::with('roles')->get())
            ->editColumn('created_at', function ($user) {
                return [
                    'display' => Carbon::parse($user->created_at)->format('d/m/Y'),
                    'timestamp' => $user->created_at->timestamp
                ];
            })
            ....

UI

          columns: [
                    {data: 'id', name: 'id', visible: false},
                    {data: 'name', name: 'name', orderable: true},    
                    {
                        name: 'created_at.timestamp',
                        data: {
                            _: 'created_at.display',
                            sort: 'created_at.timestamp'
                        }
                    },
                ],

In the UI, created_at is the name of the first param of editColumn

Upvotes: 2

Milan Akabari
Milan Akabari

Reputation: 124

Try this

$users=Checks::select(['details', DB::raw("DATE_FORMAT(checks.postingdate, '%d-%M-%Y %H:%i') as postingdate"),'description','amount','type','slip','vendor_id','category_id']);

return Datatables::of($users)->make(true);

Upvotes: 1

oreopot
oreopot

Reputation: 3450

Try the following code:

$users=Checks::select(['details','postingdate','description','amount','type','slip','vendor_id','category_id']);
return Datatables::of($users)->editColumn('postingdate', function ($user) 
{
    //change over here
    return date('d-m-Y', strtotime($user->postingdate) );
})->make(true);

Upvotes: 9

Related Questions