如何在 laravel excel 中传递参数?

How can I pass parameter in the 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为空

我该如何解决这个问题?

不幸的是,当你有一个特定的参数时,你不能使用正常的依赖注入。这是你可以做的:

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

为了将数据从控制器传递到 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();
    }
}

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

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