首页 > 解决方案 > Laravel导入Excel,传递变量时出错

问题描述

我想导入一些类别,但我还需要父类别 ID。

  public function importCategory(Request $request, $cat_id){

        $import = new CategoryImport($cat_id);
        $import->import($request->file);
        if ($import->failures()->count() > 0) {
            $message = '';
            foreach ($import->failures() as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // either heading key (if using heading row concern) or column index
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.

            }
            return redirect()->back();
        } else {
            return redirect()->back()->with('success', sprintf('Success'));
        }


    }

这是 CategoryImport.php

class CategoryImport implements WithHeadingRow, WithValidation, SkipsOnFailure,OnEachRow
{

    use Importable, SkipsFailures;

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    protected $cat_id = null;

    public function __construct(  $cat_id) {
        $category_id = $cat_id;
    }


    public function onRow(Row $row)
    {
        $row=$row->toArray();

        Category::create([

            'name' => $row['name'],
            'image' => $row['image'],
            'business_category_id' => $this->category_id,
        ]);

    }
}

所以这是错误,它说未定义的属性,我试图弄清楚但不明白。

未定义的属性:App\Imports\CategoryImport::$category_id

标签: laravelmaatwebsite-excel

解决方案


您没有正确设置 cat_id 。在您的 CategoryImport 中,您应该有:

protected $category_id = null;

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

推荐阅读