Created
August 29, 2019 12:18
-
-
Save razan-rai/676024b6f232ff2e682a6abf184b620c to your computer and use it in GitHub Desktop.
Laravel excel collection import validation and skiping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public function collection(Collection $rows) | |
| { | |
| // Initialize number | |
| $numbers = array(); | |
| foreach ($rows as $row) | |
| { | |
| $validator = Validator::make($row->toArray(), [ | |
| 'dpid' => Rule::unique('clients', 'dpid'), | |
| 'first_name' => 'required|max:255', | |
| 'last_name' => 'required|max:255', | |
| 'address' => 'required', | |
| 'mobile' => 'required', | |
| ]); | |
| //if validation fails then skip | |
| if ($validator->fails()) | |
| continue; | |
| //Skip empty rows | |
| if (!isset($row['dpid'])) | |
| continue; | |
| //Skip number previously added using in_array | |
| if (in_array($row['dpid'], $numbers)) | |
| continue; | |
| if (isset($row['dpid'])) { | |
| //import client to table | |
| $user = Client::create([ | |
| 'user_id' => Auth::user()->id, | |
| 'dpid' => $row['dpid'], | |
| 'first_name' => $row['first_name'], | |
| 'last_name' => $row['last_name'], | |
| 'address' => $row['address'], | |
| 'mobile' => $row['mobile'], | |
| 'due' => $row['due'], | |
| 'register_date' => $row['register_date'], | |
| ]); | |
| $numbers[] = $row['dpid']; | |
| //Register due in log table | |
| $log = Log::create([ | |
| 'user_id' => Auth::user()->id, | |
| 'client_id' => $user->id, | |
| 'dpid' => $row['dpid'], | |
| 'amount' => $row['due'], | |
| 'type' => 'Due', | |
| ]); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment