Files
vedant-chavan/app/Imports/UserImport.php
vedant-chavan eff0228447 first commit
2024-06-12 20:29:05 +05:30

101 lines
3.6 KiB
PHP

<?php
namespace App\Imports;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
class UserImport implements ToCollection, WithHeadingRow
{
public function collection(Collection $rows)
{
$errors = [];
foreach ($rows as $key => $row) {
$email = $row['email'];
// Check if the email is not empty and is a valid email address
if (!empty($email)) {
// Validation passed, create the user
$excelDate = $row['start_date'];
if($excelDate != null){
$unixTimestamp = ($excelDate - 25569) * 86400; // Convert Excel date to Unix timestamp
$start_date = date("Y-m-d", $unixTimestamp);
}
else{
$start_date = null;
}
$excelDate = $row['end_date'];
if($excelDate != null){
$unixTimestamp = ($excelDate - 25569) * 86400; // Convert Excel date to Unix timestamp
$end_date = date("Y-m-d", $unixTimestamp);
}
else{
$end_date = null;
}
$existingUserData = User::where('email_id',$email)->first();
if($existingUserData){
// dd($existingUserData->start_date);
// dd($row['start_date']);
if($end_date > $existingUserData->end_date)
{
// dd($existingUserData);
$data = User::where('email_id', $row['email'])->update([
'utm_source' => $row['utm_source'],
'full_name' => $row['customer_name'],
'contact_number' => $row['phone_number'],
// 'password' => Hash::make($row['password']),
'address' => $row['country'],
'fitness_goal' => $row['fitness_goal'],
'hear_about' => $row['where_did_you_hear_about_the_program'],
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
}else{
User::Create([
'email_id' => $row['email'],
'utm_source' => $row['utm_source'],
'full_name' => $row['customer_name'],
'contact_number' => $row['phone_number'],
'password' => Hash::make($row['password']),
'address' => $row['country'],
'fitness_goal' => $row['fitness_goal'],
'hear_about' => $row['where_did_you_hear_about_the_program'],
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
}
}
return $errors;
}
public function customValidationMessages($rowKey)
{
return [
'email.unique' => 'Email should be unique at row ' . ($rowKey + 1),
];
}
public function rules(): array
{
return [
'email' => 'required|unique:users,email_id',
];
}
}