可以将多个参数添加到excel导入吗?

时间:2018-12-29 13:53:00

标签: php excel laravel laravel-excel

我有一个基本表单,其中包含一个excel文件上传和一个选择选项。

选择包含一些选项。我想将用户选择的选项与文件一起传递给我的Excel::import

我尝试将另一个参数传递给导入,但返回错误。 (必须是字符串,给定数组)

可以使用Laravel excel导入吗?

控制器

public function create(Request $request)
{
    if($request->hasFile('file')) 
    {
        $package = $request->input('package');
        // how can I add $package to my import to insert it to my user model?
        Excel::import(new AccountsImport, $request->file('file'));

        return ['message' => 'Excel has been succesfully uploaded'];
    }
}

帐户导入

class AccountsImport implements ToCollection, withHeadingRow
{

    public function collection(Collection $rows)
    {
        $rows->each(function($row, $key) {
            Account::create([
                'name'   => $row['student'],
                'email'  => $row['e_mail'],
                // Want it to be possible to add my package here
                //'package' => $package
            ]);
        });
    }
}

1 个答案:

答案 0 :(得分:1)

也许您可以将自定义数据传递给您的AccountsImport类?

您将拥有一个这样的数据数组:

$data = [
    'package' => $package, 
    // other data here
]; 

然后您将执行以下操作:

Excel::import(new AccountsImport($data), $request->file('file'));

这将需要对导入类进行一些更改。

class AccountsImport implements ToCollection, withHeadingRow
{
    private $data; 

    public function __construct(array $data = [])
    {
        $this->data = $data; 
    }

    public function collection(Collection $rows)
    {
        $rows->each(function($row, $key) {
            Account::create(array_merge([
                'name'   => $row['student'],
                'email'  => $row['e_mail'],
                // Want it to be possible to add my package here
                //'package' => $package
            ], $this->data));
        });
    }
}

我看了看Laravel Excel的API,看不到任何可以满足此要求的东西,但这应该可行。