无法在 Excel::load() 之外获取对象名称值

Cannot get object name value outside Excel::load()

我正在创建联系人目录。我有一个联系人组,其中包含联系电话。我正在使用这个作曲家包 "maatwebsite/excel": "~2.1.0"。我可以在我的 contact_groups table 中保存联系人组,但我的代码无法获取新创建的联系人组的 ID。

这是我的代码。

$group = new ContactGroup();
$group->company_id = Auth::user()->company_id;
$group->group_name = $request['group_name'];
     if ($group->save()) {
        Excel::load($request->file('file')->getRealPath(), function ($reader) {
            foreach ($reader->toArray() as $key => $row) {
               $contact = new Contact();
               $contact->group_id = $group->id;
               $contact->company_id = Auth::user()->company_id;
               $contact->contact_name = $row['contact_name'];
               $contact->contact_number = $row['contact_number'];
               $contact->save();
             }
        });
        Session::flash('success','New contact group has been created!');
        return back();
     }

我收到一条错误消息 Undefined variable: group

它指向这条线$contact->group_id = $group->id;

谢谢大家!

您必须使用 use 关键字在匿名函数中传递 $group

function ($reader) use ($group) {.

Read more

更改 if 条件内的代码,使其如下所示:

Excel::load($request->file('file')->getRealPath(), function ($reader) use ($group) {
            foreach ($reader->toArray() as $key => $row) {
               $contact = new Contact();
               $contact->group_id = $group->id;
               $contact->company_id = Auth::user()->company_id;
               $contact->contact_name = $row['contact_name'];
               $contact->contact_number = $row['contact_number'];
               $contact->save();
             }
        });