Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to export file of Laravel Excel for DB query

Pass an id variable to a 'where' request to fetch database entries that match id and export these entries to an excel sheet using Laravel Excel. I can't seem to find a way to pass the variable.

My Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\MttRegistrationsExport;
use Maatwebsite\Excel\Facades\Excel;

class ExcelController extends Controller
{
    public function export($id)
    {
        return Excel::download(new MttRegistrationsExport, 'MttRegistrations.xlsx', compact('id'));
    }
}

My Export File:

<?php

namespace App\Exports;

use App\MttRegistration;
use Maatwebsite\Excel\Concerns\FromCollection;

class MttRegistrationsExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return MttRegistration::where('lifeskill_id',$id)->get()([
            'first_name', 'email'
        ]);
    }
}

My Route:

Route::get('/mtt/attendance/{id}',[
    'as' => 'mtt.attendance',
    'uses' => 'ExcelController@export']);
like image 997
Adam Avatar asked Nov 29 '22 08:11

Adam


1 Answers

Modify by passing id into the MttRegistrationsExport class.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\MttRegistrationsExport;
use Maatwebsite\Excel\Facades\Excel;

class ExcelController extends Controller
{
    public function export(Request $request)
    {
        return Excel::download(new MttRegistrationsExport($request->id), 'MttRegistrations.xlsx');
    }
}

Now let's setup a constructor so you can pass an id into the MttRegistrationsExport class.

<?php

namespace App\Exports;

use App\MttRegistration;
use Maatwebsite\Excel\Concerns\FromCollection;

class MttRegistrationsExport implements FromCollection
{


protected $id;

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

/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
    return MttRegistration::where('lifeskill_id',$this->id)->get()([
        'first_name', 'email'
    ]);
}
}
like image 81
Logan Craft Avatar answered Apr 29 '23 03:04

Logan Craft