3

I am creating a contacts directory. I have a contact group with contact numbers in it. I am using this composer package "maatwebsite/excel": "~2.1.0". I can save the contact group in my contact_groups table but my code cannot get the id of the newly created contact group.

This is my code.

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

I am getting an error saying Undefined variable: group

and it is pointing to this line $contact->group_id = $group->id;

Thanks guys!

Kim Carlo
  • 1,173
  • 3
  • 19
  • 47

2 Answers2

2

You have to pass $group inside the anonymous function using use keyword.

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

Read more

Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70
1

change your code inside of if condition, so that it looks like the following:

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();
             }
        });
oreopot
  • 3,392
  • 2
  • 19
  • 28