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']);
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'
]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With