Yajra Datatables changes datetimes incorrectly when using the datepicker in Laravel.
When using Yajra Datatables with Laravel and the jQuery UI datepicker, you might encounter an issue where datetime values are displayed incorrectly in the Datatable. This issue occurs due to the way Laravel formats the datetime values and the way Datatables expects the data to be formatted.
To resolve this issue, you need to configure both Laravel and Datatables to use the same datetime format. Here are the steps to achieve this:
- Configure Laravel to return datetime values in the desired format. You can do this by defining a custom date format in your
app/Providers/AppServiceProvider.php
file. Add the following code to theboot()
method:
use Carbon\Carbon;
use Illuminate\Support\Facades\View;
public function boot()
{
View::composer('*', function ($view) {
$view->with('carbon', function () {
return Carbon::parse(Carbon::now()->toDateString())->format('Y-m-d H:i:s');
});
});
}
This code sets a global variable $carbon
that contains the current datetime in the format Y-m-d H:i:s
. You can use this variable in your views to format datetime values.
- Configure Datatables to expect the datetime values in the same format. You can do this by setting the
datetime
column type and providing asearch
anddisplay
format when initializing the Datatable. Here's an example:
$(document).ready(function() {
$('#example').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('datatables.index') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'created_at', name: 'created_at' },
// Add other columns as needed
],
columnDefs: [
{
targets: [1], // target the datetime column
render: function (data, type, row) {
return moment(data).format('LLL'); // format the datetime as desired
}
}
],
order: [[1, 'desc']],
columns: [
{ data: 'created_at', name: 'created_at', searchable: false, orderable: false, type: 'datetime' },
// Add other columns as needed
],
initComplete: function () {
this.api().columns.adjust().draw();
},
language: {
search: "_INPUT_",
searchPlaceholder: "Search..."
}
});
});
This code sets the datetime
column type for the created_at
column and provides a search
and display
format using the moment.js
library. You can modify the render
function to format the datetime as desired.
By following these steps, you should be able to use Yajra Datatables with Laravel and the jQuery UI datepicker without encountering incorrect datetime values.