【问题标题】:Laravel Excel passing argumentLaravel Excel 传递参数
【发布时间】:2019-10-02 03:55:15
【问题描述】:

我正在尝试传递参数以过滤要导出到 Excel 的数据。

这是我的代码:

class UnitExport implements FromCollection
{
    public function collection($proj_id)
    {
        return Unit::where('project_id', $proj_id);
    }
}


class UnitController extends Controller
{
    public function index($proj_id)
    {

        return view('dev-admin.projects.units.index', ['proj_id' => $proj_id]);

    }

    public function unitExcelExport($proj_id)
    {

        return Excel::download(new UnitExport($proj_id), 'Unit.xlsx');

    }
}

当尝试这个时它说我收到一个错误说:

声明 App\Http\Controllers\Developer\Admin\UnitExport::collection($proj_id) 必须兼容 Maatwebsite\Excel\Concerns\FromCollection::collection()

【问题讨论】:

  • 我相信 UnitExport 类中的集合函数不应该有任何参数,并且 $proj_id 应该用作构造函数参数而不是集合函数。在您的代码中,“new UnitExport($proj_id)”的使用似乎不正确
  • 你应该将 $proj_id 传递给构造函数

标签: php laravel laravel-5 eloquent laravel-excel


【解决方案1】:

您不能将参数直接传递给您的集合函数。试试这个。

class UnitExport implements FromCollection
{
    protected $proj_id;

    public function __construct($proj_id)
    {
       $this->proj_id = $proj_id;
    }

    public function collection()
    {
        return Unit::where('project_id', $this->proj_id)->get();
    }
}

【讨论】:

  • 您好,我收到此错误“调用未定义的方法 Illuminate\Database\Eloquent\Builder::all()”
  • 在这一行返回 Excel::download(new UnitExport($proj_id), 'Unit.xlsx');
  • nvm 我只需要在查询时添加 get() 即可,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多