如何在laravel excel中传递参数?

时间:2018-07-28 14:17:28

标签: excel laravel laravel-5.6 laravel-excel

我从这里获得教程: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');
    }
}

我的出口是这样的:

<?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);
    }
}

我想将id参数传递给导出文件。我这样尝试,但是我没有ID。 id为空

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

不幸的是,当您具有特定参数时,不能使用常规依赖项注入。这是您可以做的:

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

现在的问题是容器不知道如何解析$ id,但是有两种解决方法。

  1. 手动传递$id

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

将您的路线定义为:

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

在您的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'));   
     });
}

然后将您的路线方法简化为:

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

答案 1 :(得分:4)

为了将数据从控制器传递到 laravel excel 函数,我们可以传递和使用如下数据

例如,我们必须像2019那样传递数据年份我们将像下面那样传递

在控制器中

Excel::download(new UsersExport(2019), 'users.xlsx');

在laravel导入文件中

class UsersExport implements FromCollection {
    private $year;

    public function __construct(int $year) 
    {
        $this->year = $year;
    }
    
    public function collection()
    {
        return Users::whereYear('created_at', $this->year)->get();
    }
}

您可以参考以下所有官方文档链接

https://docs.laravel-excel.com/3.1/architecture/objects.html#plain-old-php-object