dongxi1320 2018-12-29 13:53
浏览 95
已采纳

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

I have a basic form that contains an excel file upload and a select option.

The select contains a few options. I want to pass the selected option from the user with the file to my Excel::import

I tried passing another parameter to my import but it returns error. (has to be string, array given)

Is this possible using Laravel excel import?

Controller

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

AccountsImport

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条回答 默认 最新

  • duan4523 2018-12-29 14:10
    关注

    Maybe you could pass down custom data to your AccountsImport class?

    You would have a data array as such:

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

    You would then do something like this:

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

    That would require some changes in your import class.

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

    I took a look at Laravel Excel's API and couldn't see something that would cater for this, but this should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办