Download button does the same functionality as filter button in Laravel

I have a view in my Laravel project that lets me filter my records then I have the option to download the records to excel but when I click download, it ends up filtering the records instead of exporting to excel.

Controller:

 public function exportvehicles() 
    {
        return Excel::download(new VehicleLog, 'users.xlsx');
    }

Model:

public function collection()
    {
        return VehicleLog::all();
    }

View:

 <button  class="btn btn-primary">Export to Excel</button>

Routes:

  Route::get('users/export/', '[email protected]');

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If you did not use ajax or something. Try this.

<a href="{{"/users/export/"}}" target="_blank" class="btn btn-primary">Export to Excel</a>

Solution 2

Probable, you send post request for download process. Since the filter button is also between the form tags, it is also seen as the submit button. For this reason, you need to write type = "submit" in the upload button and type = "button" in the filter button. If you share html codes, I can answer more correctly.

Solution 3

In Vehicle Controller

Use Maatwebsite\Excel\Facades\Excel;
use App\Exports\VehicleExport;
        Use App\VehicleLog;
        
       public function exportvehicles(){
       $vehicle = VehicleLog::all();
       $data = [
       'success' => 'success'
       'vehicles' => $vehicle
       ];
       return Excel::download(new VehicleExport($data), 'Vehicledata.xlsx');
       }

and in VehhicleExport.php

public function __construct($data) {
    $this->data = $data;
}

public function view(): View
{
    //dd($this->data);   
    return view('Spreadsheets.Vehicle_data',$this->data);
}

after this you have to make balde part as how you want to export

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply