Reputation: 1223
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!
Upvotes: 3
Views: 42
Reputation: 8860
You have to pass $group
inside the anonymous function using use
keyword.
function ($reader) use ($group) {
.
Upvotes: 2
Reputation: 3450
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();
}
});
Upvotes: 1