How can I pass parameter in the laravel excel?

青春壹個敷衍的年華 提交于 2019-12-07 18:28:17

问题


I get tutorial from here : https://laravel-excel.maatwebsite.nl/docs/3.0/export/basics

<?php
...
use App\Exports\ItemsDetailsExport;
class ItemController extends Controller
{
    ...
    public function exportToExcel(ItemsDetailsExport $exporter, $id)
    {
        //dd($id); I get the result
        return $exporter->download('Summary Detail.xlsx');
    }
}

My export like this :

<?php
namespace App\Exports;
use App\Repositories\Backend\ItemDetailRepository;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Support\Facades\Input;
class ItemsDetailsExport implements FromCollection
{
    use Exportable;
    protected $itemDetailRepository;
    public function __construct(ItemDetailRepository $itemDetailRepository)
    {
        $this->itemDetailRepository = $itemDetailRepository;
    }
    public function collection()
    {
        $test  = Input::get('id');
        dd('yeah', $test);
    }
}

I want to pass id parameter to export file. I try like that, but I don't get the id. The id is null

How can I solve this problem?


回答1:


Unfortunately you can't use normal dependency injection when you have a specific parameter. This is what you can do though:

class ItemsDetailsExport implements FromCollection
{
    use Exportable;
    protected $itemDetailRepository;
    protected $id;
    public function __construct(ItemDetailRepository $itemDetailRepository, $id)
    {
        $this->itemDetailRepository = $itemDetailRepository;
        $this->id = $id; 
    }
    public function collection()
    {
        $test  = $this->id;
        dd('yeah', $test);
    }
}

Now the problem is that the container doesn't know how to resolve $id however there are two ways around this.

  1. Manual passing of $id:

    public function exportToExcel($id)
    {
        $exporter = app()->makeWith(ItemsDetailsExport::class, compact('id'));   
        return $exporter->download('Summary Detail.xlsx');
    }
    
  2. Route injection:

Define your route as:

 Route::get('/path/to/export/{itemExport}', 'ItemController@exportToExcel');

In your RouteServiceProvider.php:

public function boot() {
     parent::boot();
     //Bindings

     Route::bind('itemExport', function ($id) { //itemExport must match the {itemExport} name in the route definition
         return app()->makeWith(ItemsDetailsExport::class, compact('id'));   
     });
}

Then your route method is simplified as:

public function exportToExcel(ItemsDetailsExport $itemExport)
{
    //It will be injected based on the parameter you pass to the route
    return $itemExport->download('Summary Detail.xlsx');
}


来源:https://stackoverflow.com/questions/51572197/how-can-i-pass-parameter-in-the-laravel-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!