Conixs
132
4
Laravel

How to add export buttons to yajra/laravel-datatables?

Posted 1 month ago by Conixs

Hello everyone! I'm already using it to render my data as datatable, but now I wish to be able to export it on PDF and XLS.

  1. Do I need to add the Buttons Plugin to be able to achieve it?
  2. Do I need to create a new datatable model - php artisan datatables:make - for each table?
public function index(Request $request)
    {
        if($request->ajax()) {
            $model = Shift::withTrashed()->select('shifts.*');
            return $this->dataTable
                ->eloquent($model)
                ->addColumn('deleted_at', function (Shift $shift) {
                    if($shift->trashed())
                        return '<span class="status--denied">INATIVO</span>';
                    return '<span class="status--process">ATIVO</span>';
                })
                ->addColumn('edit', function (Shift $shift) {
                    return '<div class="table-data-feature"><a href="'.route('shifts.edit', ['shift' => $shift]).'" class="item" data-toggle="tooltip" data-placement="top" data-original-title="Editar"><i class="zmdi zmdi-edit"></i></a></div>';
                })
                ->rawColumns(['deleted_at', 'edit'])
                ->make(true);
        }

        $shifts = Shift::withTrashed()->get();
        return view('shifts.index', ['shifts' => $shifts]);
}
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript"
        src="https://gyrocode.github.io/jquery-datatables-pageLoadMore/1.0.1/js/dataTables.pageLoadMore.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var table = $('.table-data2').DataTable({
            serverSide: true,
            "pageLength": 5,
            dom: 'frt',
            ajax: '{{route('shifts.index')}}',
            columns: [
                {data: 'name', name: 'name'},
                {data: 'deleted_at', name: 'deleted_at', 'searchable': false},
                {data: 'edit', name:'edit', 'searchable': false, 'orderable': false}
            ],
            drawCallback: function () {
                if ($('.au-btn-load').is(':visible')) {
                    $('html, body').animate({
                        scrollTop: $('.au-btn-load').offset().top
                    }, 1000);
                }

                $('.au-btn-load').toggle(this.api().page.hasMore());
            }
        });

        $('.au-btn-load').on('click', function () {
            table.page.loadMore();
        });
    });
</script>

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.