Search code examples
phpjquerylaraveldatatablesadminlte

How to add custom filters to jeroennoten Laravel-AdminLTE Datatables?


hope that you are fine and you are able to help me... I am starting a project with laravel and admin lte, so i looked for the best way to integrate these two and there is the mentioned package: jeroennoten Laravel-AdminLTE.

It brings a way to integrate jquery datatables, but the setup and data source of these are from php directly (as you may know if you are familiar with the package).

Basically you initialize the Datatable from the blade component of Datatables. That means you cannot setup and configure datatables as usual because when you want to initialize it in js like this:

const table = new DataTable('#table2');

Because it will show an alert saying you cannot reinitialize the datatable. This means that you cannot make all the adjustments to the datatable from js/jquery as you usually do. So i dont know how to do custom filters, for example a date filter, from a date to another.

If there is a solution to this would be perfect, if not you can tell me a suggestion of what to do. Thanks!


Solution

  • Not sure exactly what you are asking here, need more information. But, if you are trying to reload a data table you can use:

    $('#table2').DataTable().ajax.reload();
    

    If you want a date filter you will need to pass the from_date and to_date parameters to your controller. Generally you will use 2 inputs to pass this to your controller via ajax. Below is a basic example:

    $(document).on('click', '#filter_submit_btn', function(e){
        e.preventDefault();
        // get from and to input values
        let from_date = $('#from_input').val();
        let to_date = $('#to_input).val();
        $.ajax({
            type: "POST",
            url: "controllerRoute",
            data: {
                   fromDate : from_date,
                   toDate : to_date,
            },  
            dataType: "JSON",
          success: function (response) {
              //reload datatable with new data
              $('#table2').DataTable().ajax.reload();
          }
        });
    

    Then in your controller you need to parse the inputs in your query:

    public function index(Request $request){
        if ($request->ajax()) {
             $query = Model::whereDate('from_date', '>=', $request->fromDate)->whereDate('to_date', '<=' , $request->toDate)->get()
             return json_encode($query);
        }
    }