编程语言
首页 > 编程语言> > php-无法在Excel :: load()之外获取对象名称值

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

作者:互联网

我正在创建一个联系人目录.我有一个包含联系人号码的联系人组.我正在使用此作曲家程序包“ maatwebsite / excel”:“〜2.1.0”.我可以将联系人组保存在contact_groups表中,但我的代码无法获取新创建的联系人组的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();
     }

我收到一条错误消息:未定义变量:组

并指向此行$contact-> group_id = $group-> id;

多谢你们!

解决方法:

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

函数($reader)使用($group){.

Read more

标签:maatwebsite-excel,laravel,php
来源: https://codeday.me/bug/20191108/2007513.html