PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

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

 April 19, 2022     excel, laravel, parameters, push     No comments   

Issue

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

Solution

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


Answered By - Logan Craft
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing