How to export data to excel with certain criteria in Laravel 8
Tags: laravel
Published: 2022-03-18 15:32:44

I tried to export excel with criteria using ajax,
but always fails when exporting with criteria,
and I always get the error:
The GET method is not supported for this route. Supported methods: POST.

can anyone help me here?

here's the code:

View Code :

```
`        $(function () {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
           let tblMassy =  $('#tblMassy').DataTable({
           processing: true,
           serverSide : true,
           autoWidth : false,
           pageLength : 10 ,
           "order" : [[ 0, "desc"]],
           ajax : '{{ URL::to('http://localhost:8000/admin/getMassy') }}',

           columnDefs: [
                {   
                    'targets': 0,
                    'checkboxes': true
                }
            ],
                columns : [
                    {data : 'id' , name: 'id'},
                    {data : 'assymainharness' , name: 'assymainharness'},
                    {data : 'assyab' , name: 'assyab'},
                    {data : 'assyab1' , name: 'assyab1'},
                    {data : 'assyab2' , name: 'assyab2'},
                    {data : 'assyab3' , name: 'assyab3'},
                    {data : 'type' , name: 'type'},
                    {data : 'assycode' , name: 'assycode'},
                    {data : 'suffixlevel' , name: 'suffixlevel'},
                    {data : 'desccarline' , name: 'desccarline'},
                    {data : 'factory' , name: 'factory'},
                    {data : 'customer' , name: 'customer'},
                    {data : 'name' , name: 'name'},
                    {data : 'Actions' , name: 'Actions'}
                ]
            });

            $('#export').click(function (e) {
            let rows_selected = tblMassy.column(0).checkboxes.selected();
                        if (rows_selected.length >= 1)  {

                            $.each(rows_selected, function(index, rowId){

                                // console.log( "http://localhost:8000/eksportfilter/" + rowId ) ;
                                // location.href= "/eksportfilter/" + rowId;
                                $.ajax({
                                    type:'POST',
                                    url: "http://localhost:8000/eksportfilter/" + rowId,
                                    dataType: "JSON",
                                    success: function (response) {
                                        console.log( response )
                                    }
                                });   
                            });
                                console.log(rows_selected.length);

                                swal("Good job!", "Eksport data successfully!", "success");
                                
                                $('#tblMassy').DataTable().ajax.reload();
                                // location.reload();
                        } else {
                            swal("Failed Export!", "No Data Delected!", "error");
                        }
        });

            $('.show_confirm').click(function(event) {
                var form =  $(this).closest("form");
                var name = $(this).data("name");
                event.preventDefault();
                swal({
                    title: `Are you sure you want to delete this record?`,
                    text: "If you delete this, it will be gone forever.",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                })
                .then((willDelete) => {
                    if (willDelete) {
                        // $('#btn_delete_all').click(function (e) {
                            // e.preventDefault();
                        let rows_selected = tblMassy.column(0).checkboxes.selected();
                        console.log( rows_selected.length );
                        if (rows_selected.length >= 1)  {

                            $.each(rows_selected, function(index, rowId){

                                console.log( "http://localhost:8000/admin/deleteAssy/" + rowId ) ;

                                $.ajax({
                                    type: "POST",
                                    url: "http://localhost:8000/admin/deleteAssy/" + rowId ,
                                    dataType: "JSON",
                                    success: function (response) {
                                        console.log( response )
                                    }
                                });
                            });
                                console.log(rows_selected.length);

                                swal("Good job!", "Delete data successfully!", "success");
                                
                                $('#tblMassy').DataTable().ajax.reload();
                                location.reload();
                        } else {
                            swal("Failed    !", "No Data Delected!", "error");
                        }
                        // });
                    }
                });
            });

                   // submit btndelete all

        });
    </script>`
```

Route :

```
` Route::post('eksportfilter/{id}', [MAssyController::class , 'eksportfilter'])->name('eksportfilter.post');`
```

Controller :

```
` public function eksportfilter($id)
    {
     return (new TransactionsExportFilter($id))->download('Master-Assy-list-Filter.xlsx');
    }`
```

Maatwebsite\Excel :

```
`namespace App\Exports;

use App\Models\m_assy;

use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;

class TransactionsExportFilter implements FromQuery, WithHeadings
{
    use Exportable;

    public $id;   //HERE

    public function __construct(string $keyword)
    {
        $this->id = $keyword;
    }


    /**
    * @return \Illuminate\Support\Collection
    */
    public function query()
    {
        return m_assy::query()->where('id', 'like', '%' . $this->id . '%');
    }
  
    public function headings(): array
    {
        return [
            'id',
            'assymainharness',
            'assyab',
            'assyab1',
            'assyab2',
            'assyab3',
            'type',
            'assycode',
            'suffixlevel',
            'desccarline',
            'factory',
            'customer',
        ];
}`
```