public function handle_file_upload(Request $request) { $file = $request->file('csv'); $duplicated = 0; $imported = 0; $list_id = $request->list_id; Excel::load($file->getRealPath(), function ($reader) use(&$duplicated, &$imported, $list_id) { // Getting all results $results = $reader->all(); foreach ($results as $i) { $new_email = extract_email_from_str($i->email); $subscriber = Subscriber::where('email', $new_email)->first(); if ($subscriber == null) { if ($new_email != null) { $subscriber = new Subscriber(); $subscriber->email = $new_email; $subscriber->name = $i->name; $subscriber->save(); $subscriber->subscribers_lists()->attach($list_id); $imported += 1; } } else { $count = $subscriber->subscribers_lists()->where('id', $list_id)->count(); if ($count > 0) { $duplicated += 1; } else { $subscriber->subscribers_lists()->attach($list_id); $imported += 1; } $subscriber->name = $i->name; $subscriber->save(); } } Session::flash('imported', $imported); Session::flash('duplicated', $duplicated); })->get(); return redirect('manage/upload_subscribers_csv?list_id=' . $list_id); }