Skip to content

Instantly share code, notes, and snippets.

@razan-rai
Created August 29, 2019 12:18
Show Gist options
  • Select an option

  • Save razan-rai/676024b6f232ff2e682a6abf184b620c to your computer and use it in GitHub Desktop.

Select an option

Save razan-rai/676024b6f232ff2e682a6abf184b620c to your computer and use it in GitHub Desktop.
Laravel excel collection import validation and skiping
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