9

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']);

1 Answer 1

38

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'
    ]);
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Worked perfectly! Thank you so much! I just had to fix the get request to - get(['first_name', etc.]). Again thank you so much Logan! You have been a real help!
Good and better way you explained ... i like it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.