admin管理员组

文章数量:1399260

I am working with an Excel file where users input dates, and I need to validate whether the entered date is valid (i.e., it actually exists). For example, if a user provides 31-02-2025, it should trigger a validation error since February 31st does not exist.

I am importing this data into my system and need a way to detect such invalid dates before further processing.

id; $riskRegisterTypeId = RiskRegisterType::ermRisk()->id; foreach ($rows as $value) { $risk = new Risk(); $risk->title = $value['title']; $risk->is_corporate = false; $risk->is_functional = true; $risk->is_registered = false; $risk->risk_register_type_id = $riskRegisterTypeId; $risk->risk_classification_id = $value['risk_classification_id']; $risk->description = $value['description']; $risk->risk_category_id = $value['risk_category_id']; $risk->risk_sub_category_id = $value['risk_sub_category_id']; $risk->risk_date = Date::excelToDateTimeObject($value['risk_identification_date'])->format('Y-m-d'); $risk->next_review_user_level = 1; $risk->journey_next_review_user_level = 1; $risk->is_workflow = true; $risk->risk_owner_id = $value['risk_owner_id']; $risk->created_by = Auth::user()->id; $risk->risk_status_id = $statusId; $riskImpactsArray = explode(',', $value['risk_consequences']); //Save risk impacts $risk_consequences = []; $riskImpacts = []; if ($riskImpactsArray) { foreach ($riskImpactsArray as $riskImpactTitle) { if ((str_replace(' ', '', $riskImpactTitle))) { $risk_consequences[] = ['title' => $riskImpactTitle]; } } foreach ($risk_consequences as $riskImpactRow) { $riskImpact = new RiskImpact(); $riskImpact->title = $riskImpactRow['title']; $riskImpact->created_by = Auth::user()->id; $riskImpact->status_id = Status::active()->id; $riskImpacts[] = $riskImpact; } } $riskCausesArray = explode(',', $value['risk_causes']); $risk_Causes = []; $riskCauses = []; //Save risk causes if ($riskCausesArray) { foreach ($riskCausesArray as $riskCauseTitle) { if ((str_replace(' ', '', $riskCauseTitle))) { $risk_Causes[] = ['title' => $riskCauseTitle]; } } foreach ($risk_Causes as $riskCauseRow) { $riskCause = new RiskCause(); $riskCause->title = $riskCauseRow['title']; $riskCause->created_by = Auth::user()->id; $riskCause->status_id = Status::active()->id; $riskCauses[] = $riskCause; } } $riskTypeIds = explode(",", $value['risk_nature_ids']); $riskSources = explode(',', $value['risk_source_ids']); $riskAreaIds = explode(',', $value['risk_driver_ids']); $userIds = explode(',', $value['responsible_user_ids']); $divisionIds = explode(',', $value['division_ids']); $departmentIds = explode(',', $value['department_ids']); $sectionIds = explode(',', $value['section_ids']); $latestFunctionalRisk = Risk::where('is_functional', true) ->leftJoin('risk_department', 'risks.id', 'risk_department.risk_id') ->whereIn('risk_department.department_id', $departmentIds) ->latest('id') ->first(); if ($latestFunctionalRisk) { $matches = (int) filter_var($latestFunctionalRisk->reference_code, FILTER_SANITIZE_NUMBER_INT); } $latestFunctionalRiskId = $latestFunctionalRisk ? (int)$matches : 0; $departments = Department::select('id', 'code')->whereIn('id', $departmentIds)->get(); $code = ""; foreach ($departments as $department) { $code .= "$department->code"; } $isReferenceCodeEnabled = ErmSetting::enableReferenceCode(); if ($isReferenceCodeEnabled) { $risk->reference_code = $this->settingReferenceCode($risk, $value); $risk->save(); } else $risk->reference_code = $code . sprintf("%06d", $latestFunctionalRiskId + 1); $risk->save(); $risk->riskImpacts()->saveMany($riskImpacts); $risk->riskCauses()->saveMany($riskCauses); if (OrganizationSettings::getIsSubsidiary()) { $anizationIds = explode(',', $value['anization_ids']); $risk->anizations()->sync($anizationIds); } if (OrganizationSettings::getIsDivision()) { $divisionIds = explode(',', $value['division_ids']); $risk->divisions()->sync($divisionIds); } if (OrganizationSettings::getIsDepartment()) { $departmentIds = explode(',', $value['department_ids']); $risk->departments()->sync($departmentIds); } if (OrganizationSettings::getIsSection()) { $sectionIds = explode(',', $value['section_ids']); $risk->sections()->sync($sectionIds); } if (OrganizationSettings::getIsSubSection()) { $subSectionIds = explode(',', $value['sub_section_ids']); $risk->subSections()->sync($subSectionIds); } $risk->riskTypes()->sync($riskTypeIds); $risk->riskSources()->sync($riskSources); $risk->riskAreas()->sync($riskAreaIds); $risk->responsibleUsers()->sync($userIds); $workflow = Workflow::where('module_id', Module::$ermRisk)->first(); if ($workflow) { $workflowId = $workflow->id; //save the workflow users $workflowItems = Workflow::findOrFail($workflowId)->items; foreach ($workflowItems as $item) { $riskWorkFlowItem = getWorkFlowItemObject(new RiskWorkflowItem(), $item); $riskWorkFlowItem->risk_id = $risk->id; $riskWorkFlowItem->save(); setWorkflowItemUser($riskWorkFlowItem, $item); } } } } public function rules(): array { Validator::extend('validate_exists', function ($attribute, $value, $parameters, $validator) { $tablename = $parameters[0]; $field = $parameters[1]; $tablename = str_replace('*.', '', $tablename); $params = explode(',', $value); foreach ($params as $value) { if (!DB::table($tablename)->where($field, $value)->exists()) { return false; } } return true; }, __("validation.invalid_data")); Validator::replacer('validate_exists', function ($message, $attribute, $rule, $parameters, $value) { $row = explode('.', $attribute)[0]; $validationmessage = str_replace(':attribute', $attribute, $message); $validationmessage = str_replace(':row', $row, $validationmessage); return $validationmessage; }); return [ '*.title' => 'required', '*.risk_classification_id' => 'required|integer|exists:risk_classifications,id', '*.description' => 'nullable:risks,description', '*.risk_category_id' => 'required|integer|exists:risk_categories,id', '*.risk_sub_category_id' => 'required|integer|exists:risk_sub_categories,id', // '*.risk_date' => 'required|date|date_format:"Y-m-d"', '*.risk_identification_date' => 'required', '*.risk_owner_id' => 'required|integer|exists:users,id', '*.risk_consequences' => 'nullable', '*.risk_causes' => 'nullable', '*.risk_nature_ids' => "required|validate_exists:risk_types,id", '*.risk_source_ids' => "required|validate_exists:risk_sources,id", '*.risk_driver_ids' => "required|validate_exists:risk_areas,id", '*.risk_owner_id' => "required|exists:users,id", '*.responsible_user_ids' => "required|validate_exists:users,id", '*anization_ids' => Rule::requiredIf((OrganizationSettings::getIsSubsidiary())) . "|validate_exists:anizations,id", '*.division_ids' => Rule::requiredIf(OrganizationSettings::getIsDivision()) . "|validate_exists:divisions,id", '*.department_ids' => Rule::requiredIf(OrganizationSettings::getIsDepartment()) . "|validate_exists:departments,id", '*.section_ids' => Rule::requiredIf(OrganizationSettings::getIsSection()) . "|validate_exists:sections,id", '*.sub_section_ids' => Rule::requiredIf((OrganizationSettings::getIsSubSection())) . "|validate_exists:sub_sections,id", ]; } public function customValidationAttributes(): array { return [ "title" => __("labels.title"), "risk_classification_id" => __("labels.risk_classification_id"), "description" => __("labels.description"), "risk_category_id" => __("labels.risk_category_id"), "risk_sub_category_id" => __("labels.risk_sub_category_id"), "risk_identification_date" => __("labels.risk_identification_date"), "risk_owner_id" => __("labels.risk_owner_id"), "risk_consequences" => __("labels.risk_consequences"), "risk_causes" => __("labels.risk_causes"), "risk_nature_ids" => __("labels.risk_nature_ids"), "risk_source_ids" => __("labels.risk_source_ids"), "risk_driver_ids" => __("labels.risk_driver_ids"), "responsible_user_ids" => __("labels.responsible_user_ids"), "anization_ids" => __("labelsanization_ids"), "division_ids" => __("labels.division_ids"), "department_ids" => __("labels.department_ids"), "section_ids" => __("labels.section_ids"), "sub_section_ids" => __("labels.sub_section_ids") ]; } public function sheets(): array { return [ 0 => $this, ]; } public function settingReferenceCode($risk, $value, $is_update = null) { $referenceCodeSettings = ErmSettingReferenceCode::orderBy('order')->get(); $referenceCode = ""; $newReferenceCode = 0; $codeDivider = !empty(ErmSettingReferenceCode::where('reference_type', 'code-divider')->first()) ? ErmSettingReferenceCode::where('reference_type', 'code-divider')->first()->title : '/'; if (!$risk->is_corporate) { $latestFunctionalRisk = Risk::where('is_functional', true) ->leftJoin('risk_division','risks.id','risk_division.risk_id') ->whereIn('risk_division.division_id', [$value['division_ids']]) ->latest('id') ->first(); if ($latestFunctionalRisk) { $latestId = explode($codeDivider, $latestFunctionalRisk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); } } else { $latestCorporateRisk = Risk::where('is_corporate', true)->latest('id')->first(); if ($latestCorporateRisk) { $latestId = explode($codeDivider, $latestCorporateRisk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); } } foreach ($referenceCodeSettings as $key => $referenceCodeSetting) { if ($referenceCodeSetting->order) { switch ($referenceCodeSetting->reference_type) { case 'division': if (!empty($value['division_ids'])) { $divisionIds = array_filter(explode(',', $value['division_ids']), 'strlen'); $referenceCode .= Division::findOrFail($divisionIds[0])->code; $referenceCode .= $codeDivider; } break; case 'department': if (!empty($value['department_ids'])) { $departmentIds = array_filter(explode(',', $value['department_ids']), 'strlen'); $referenceCode .= Department::findOrFail($departmentIds[0])->code; $referenceCode .= $codeDivider; } break; case 'section': if (!empty($value['section_ids'])) { $sectionIds = array_filter(explode(',', $value['section_ids']), 'strlen'); $referenceCode .= Section::findOrFail($sectionIds[0])->code; $referenceCode .= $codeDivider; } break; case 'company-code': case 'level': case 'prefix': case 'risk-prefix': $referenceCode .= $referenceCodeSetting->title; $referenceCode .= $codeDivider; break; case 'year': $referenceCode .= date("Y"); $referenceCode .= $codeDivider; break; default: // Handle any other cases if needed } } } if ($is_update == true) { $latestId = explode($codeDivider, $risk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); $referenceCode .= sprintf("%04d", $newReferenceCode); } else { $referenceCode .= sprintf("%04d", $newReferenceCode + 1); } return $referenceCode; } public function registerEvents(): array { return [ BeforeImport::class => function (BeforeImport $event) { $this->mapHeaderRow($event); } ]; } /** * Get the header mappings for the import. * Should match the column order from the template export * @see App\Exports\ERMRiskManagement\ERMRiskERMRiskTemplateExport@sheets * @return array */ public function getHeaderMappings() { $standardColumnNames = [ 'sl', 'risk_classification_id', 'title', 'description', 'risk_consequences', 'risk_causes', 'risk_nature_ids', 'risk_source_ids', 'risk_category_id', 'risk_sub_category_id', 'risk_driver_ids', 'risk_identification_date' ]; if (OrganizationSettings::getIsSubsidiary()) { $standardColumnNames[] = 'anization_ids'; } if (OrganizationSettings::getIsDivision()) { $standardColumnNames[] = 'division_ids'; } if (OrganizationSettings::getIsDepartment()) { $standardColumnNames[] = 'department_ids'; } if (OrganizationSettings::getIsSection()) { $standardColumnNames[] = 'section_ids'; } if (OrganizationSettings::getIsSubSection()) { $standardColumnNames[] = 'sub_section_ids'; } $standardColumnNames[] = 'responsible_user_ids'; $standardColumnNames[] = 'risk_owner_id'; $this->headerMappings = []; foreach ($standardColumnNames as $index =>$standardColumnName) { foreach(Language::all() as $language) { $this->headerMappings[$index][$standardColumnName][] = Str::slug(__("labels.{$standardColumnName}", [], $language->code), '_'); } } } private function mapHeaderRow(BeforeImport $event) { $this->getHeaderMappings(); $worksheet = $event->getDelegate()->getActiveSheet(); $headerRow = $worksheet->getRowIterator(1)->current()->getCellIterator(); foreach ($headerRow as $cell) { $headerValue = Str::slug($cell->getValue(), "_"); // $columnLetter = $cell->getColumn(); // Convert letter index to numerical index (0, 1, 2, ...) $columnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($columnLetter) - 1; if (!isset($this->headerMappings[$columnIndex])) { break; } // Find the correct key in header mappings $header = $this->headerMappings[$columnIndex]; foreach($header as $expectedHeader => $aliases) { if (in_array($headerValue, $aliases)) { $cell->setValue($expectedHeader); // Set the cell to the standard header break; } } } } } Can anyone edit this code and share it

I am working with an Excel file where users input dates, and I need to validate whether the entered date is valid (i.e., it actually exists). For example, if a user provides 31-02-2025, it should trigger a validation error since February 31st does not exist.

I am importing this data into my system and need a way to detect such invalid dates before further processing.

id; $riskRegisterTypeId = RiskRegisterType::ermRisk()->id; foreach ($rows as $value) { $risk = new Risk(); $risk->title = $value['title']; $risk->is_corporate = false; $risk->is_functional = true; $risk->is_registered = false; $risk->risk_register_type_id = $riskRegisterTypeId; $risk->risk_classification_id = $value['risk_classification_id']; $risk->description = $value['description']; $risk->risk_category_id = $value['risk_category_id']; $risk->risk_sub_category_id = $value['risk_sub_category_id']; $risk->risk_date = Date::excelToDateTimeObject($value['risk_identification_date'])->format('Y-m-d'); $risk->next_review_user_level = 1; $risk->journey_next_review_user_level = 1; $risk->is_workflow = true; $risk->risk_owner_id = $value['risk_owner_id']; $risk->created_by = Auth::user()->id; $risk->risk_status_id = $statusId; $riskImpactsArray = explode(',', $value['risk_consequences']); //Save risk impacts $risk_consequences = []; $riskImpacts = []; if ($riskImpactsArray) { foreach ($riskImpactsArray as $riskImpactTitle) { if ((str_replace(' ', '', $riskImpactTitle))) { $risk_consequences[] = ['title' => $riskImpactTitle]; } } foreach ($risk_consequences as $riskImpactRow) { $riskImpact = new RiskImpact(); $riskImpact->title = $riskImpactRow['title']; $riskImpact->created_by = Auth::user()->id; $riskImpact->status_id = Status::active()->id; $riskImpacts[] = $riskImpact; } } $riskCausesArray = explode(',', $value['risk_causes']); $risk_Causes = []; $riskCauses = []; //Save risk causes if ($riskCausesArray) { foreach ($riskCausesArray as $riskCauseTitle) { if ((str_replace(' ', '', $riskCauseTitle))) { $risk_Causes[] = ['title' => $riskCauseTitle]; } } foreach ($risk_Causes as $riskCauseRow) { $riskCause = new RiskCause(); $riskCause->title = $riskCauseRow['title']; $riskCause->created_by = Auth::user()->id; $riskCause->status_id = Status::active()->id; $riskCauses[] = $riskCause; } } $riskTypeIds = explode(",", $value['risk_nature_ids']); $riskSources = explode(',', $value['risk_source_ids']); $riskAreaIds = explode(',', $value['risk_driver_ids']); $userIds = explode(',', $value['responsible_user_ids']); $divisionIds = explode(',', $value['division_ids']); $departmentIds = explode(',', $value['department_ids']); $sectionIds = explode(',', $value['section_ids']); $latestFunctionalRisk = Risk::where('is_functional', true) ->leftJoin('risk_department', 'risks.id', 'risk_department.risk_id') ->whereIn('risk_department.department_id', $departmentIds) ->latest('id') ->first(); if ($latestFunctionalRisk) { $matches = (int) filter_var($latestFunctionalRisk->reference_code, FILTER_SANITIZE_NUMBER_INT); } $latestFunctionalRiskId = $latestFunctionalRisk ? (int)$matches : 0; $departments = Department::select('id', 'code')->whereIn('id', $departmentIds)->get(); $code = ""; foreach ($departments as $department) { $code .= "$department->code"; } $isReferenceCodeEnabled = ErmSetting::enableReferenceCode(); if ($isReferenceCodeEnabled) { $risk->reference_code = $this->settingReferenceCode($risk, $value); $risk->save(); } else $risk->reference_code = $code . sprintf("%06d", $latestFunctionalRiskId + 1); $risk->save(); $risk->riskImpacts()->saveMany($riskImpacts); $risk->riskCauses()->saveMany($riskCauses); if (OrganizationSettings::getIsSubsidiary()) { $anizationIds = explode(',', $value['anization_ids']); $risk->anizations()->sync($anizationIds); } if (OrganizationSettings::getIsDivision()) { $divisionIds = explode(',', $value['division_ids']); $risk->divisions()->sync($divisionIds); } if (OrganizationSettings::getIsDepartment()) { $departmentIds = explode(',', $value['department_ids']); $risk->departments()->sync($departmentIds); } if (OrganizationSettings::getIsSection()) { $sectionIds = explode(',', $value['section_ids']); $risk->sections()->sync($sectionIds); } if (OrganizationSettings::getIsSubSection()) { $subSectionIds = explode(',', $value['sub_section_ids']); $risk->subSections()->sync($subSectionIds); } $risk->riskTypes()->sync($riskTypeIds); $risk->riskSources()->sync($riskSources); $risk->riskAreas()->sync($riskAreaIds); $risk->responsibleUsers()->sync($userIds); $workflow = Workflow::where('module_id', Module::$ermRisk)->first(); if ($workflow) { $workflowId = $workflow->id; //save the workflow users $workflowItems = Workflow::findOrFail($workflowId)->items; foreach ($workflowItems as $item) { $riskWorkFlowItem = getWorkFlowItemObject(new RiskWorkflowItem(), $item); $riskWorkFlowItem->risk_id = $risk->id; $riskWorkFlowItem->save(); setWorkflowItemUser($riskWorkFlowItem, $item); } } } } public function rules(): array { Validator::extend('validate_exists', function ($attribute, $value, $parameters, $validator) { $tablename = $parameters[0]; $field = $parameters[1]; $tablename = str_replace('*.', '', $tablename); $params = explode(',', $value); foreach ($params as $value) { if (!DB::table($tablename)->where($field, $value)->exists()) { return false; } } return true; }, __("validation.invalid_data")); Validator::replacer('validate_exists', function ($message, $attribute, $rule, $parameters, $value) { $row = explode('.', $attribute)[0]; $validationmessage = str_replace(':attribute', $attribute, $message); $validationmessage = str_replace(':row', $row, $validationmessage); return $validationmessage; }); return [ '*.title' => 'required', '*.risk_classification_id' => 'required|integer|exists:risk_classifications,id', '*.description' => 'nullable:risks,description', '*.risk_category_id' => 'required|integer|exists:risk_categories,id', '*.risk_sub_category_id' => 'required|integer|exists:risk_sub_categories,id', // '*.risk_date' => 'required|date|date_format:"Y-m-d"', '*.risk_identification_date' => 'required', '*.risk_owner_id' => 'required|integer|exists:users,id', '*.risk_consequences' => 'nullable', '*.risk_causes' => 'nullable', '*.risk_nature_ids' => "required|validate_exists:risk_types,id", '*.risk_source_ids' => "required|validate_exists:risk_sources,id", '*.risk_driver_ids' => "required|validate_exists:risk_areas,id", '*.risk_owner_id' => "required|exists:users,id", '*.responsible_user_ids' => "required|validate_exists:users,id", '*.anization_ids' => Rule::requiredIf((OrganizationSettings::getIsSubsidiary())) . "|validate_exists:anizations,id", '*.division_ids' => Rule::requiredIf(OrganizationSettings::getIsDivision()) . "|validate_exists:divisions,id", '*.department_ids' => Rule::requiredIf(OrganizationSettings::getIsDepartment()) . "|validate_exists:departments,id", '*.section_ids' => Rule::requiredIf(OrganizationSettings::getIsSection()) . "|validate_exists:sections,id", '*.sub_section_ids' => Rule::requiredIf((OrganizationSettings::getIsSubSection())) . "|validate_exists:sub_sections,id", ]; } public function customValidationAttributes(): array { return [ "title" => __("labels.title"), "risk_classification_id" => __("labels.risk_classification_id"), "description" => __("labels.description"), "risk_category_id" => __("labels.risk_category_id"), "risk_sub_category_id" => __("labels.risk_sub_category_id"), "risk_identification_date" => __("labels.risk_identification_date"), "risk_owner_id" => __("labels.risk_owner_id"), "risk_consequences" => __("labels.risk_consequences"), "risk_causes" => __("labels.risk_causes"), "risk_nature_ids" => __("labels.risk_nature_ids"), "risk_source_ids" => __("labels.risk_source_ids"), "risk_driver_ids" => __("labels.risk_driver_ids"), "responsible_user_ids" => __("labels.responsible_user_ids"), "anization_ids" => __("labels.anization_ids"), "division_ids" => __("labels.division_ids"), "department_ids" => __("labels.department_ids"), "section_ids" => __("labels.section_ids"), "sub_section_ids" => __("labels.sub_section_ids") ]; } public function sheets(): array { return [ 0 => $this, ]; } public function settingReferenceCode($risk, $value, $is_update = null) { $referenceCodeSettings = ErmSettingReferenceCode::orderBy('order')->get(); $referenceCode = ""; $newReferenceCode = 0; $codeDivider = !empty(ErmSettingReferenceCode::where('reference_type', 'code-divider')->first()) ? ErmSettingReferenceCode::where('reference_type', 'code-divider')->first()->title : '/'; if (!$risk->is_corporate) { $latestFunctionalRisk = Risk::where('is_functional', true) ->leftJoin('risk_division','risks.id','risk_division.risk_id') ->whereIn('risk_division.division_id', [$value['division_ids']]) ->latest('id') ->first(); if ($latestFunctionalRisk) { $latestId = explode($codeDivider, $latestFunctionalRisk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); } } else { $latestCorporateRisk = Risk::where('is_corporate', true)->latest('id')->first(); if ($latestCorporateRisk) { $latestId = explode($codeDivider, $latestCorporateRisk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); } } foreach ($referenceCodeSettings as $key => $referenceCodeSetting) { if ($referenceCodeSetting->order) { switch ($referenceCodeSetting->reference_type) { case 'division': if (!empty($value['division_ids'])) { $divisionIds = array_filter(explode(',', $value['division_ids']), 'strlen'); $referenceCode .= Division::findOrFail($divisionIds[0])->code; $referenceCode .= $codeDivider; } break; case 'department': if (!empty($value['department_ids'])) { $departmentIds = array_filter(explode(',', $value['department_ids']), 'strlen'); $referenceCode .= Department::findOrFail($departmentIds[0])->code; $referenceCode .= $codeDivider; } break; case 'section': if (!empty($value['section_ids'])) { $sectionIds = array_filter(explode(',', $value['section_ids']), 'strlen'); $referenceCode .= Section::findOrFail($sectionIds[0])->code; $referenceCode .= $codeDivider; } break; case 'company-code': case 'level': case 'prefix': case 'risk-prefix': $referenceCode .= $referenceCodeSetting->title; $referenceCode .= $codeDivider; break; case 'year': $referenceCode .= date("Y"); $referenceCode .= $codeDivider; break; default: // Handle any other cases if needed } } } if ($is_update == true) { $latestId = explode($codeDivider, $risk->reference_code); $newReferenceCode = (int) abs(filter_var(end($latestId), FILTER_SANITIZE_NUMBER_INT)); $referenceCode .= sprintf("%04d", $newReferenceCode); } else { $referenceCode .= sprintf("%04d", $newReferenceCode + 1); } return $referenceCode; } public function registerEvents(): array { return [ BeforeImport::class => function (BeforeImport $event) { $this->mapHeaderRow($event); } ]; } /** * Get the header mappings for the import. * Should match the column order from the template export * @see App\Exports\ERMRiskManagement\ERMRiskERMRiskTemplateExport@sheets * @return array */ public function getHeaderMappings() { $standardColumnNames = [ 'sl', 'risk_classification_id', 'title', 'description', 'risk_consequences', 'risk_causes', 'risk_nature_ids', 'risk_source_ids', 'risk_category_id', 'risk_sub_category_id', 'risk_driver_ids', 'risk_identification_date' ]; if (OrganizationSettings::getIsSubsidiary()) { $standardColumnNames[] = 'anization_ids'; } if (OrganizationSettings::getIsDivision()) { $standardColumnNames[] = 'division_ids'; } if (OrganizationSettings::getIsDepartment()) { $standardColumnNames[] = 'department_ids'; } if (OrganizationSettings::getIsSection()) { $standardColumnNames[] = 'section_ids'; } if (OrganizationSettings::getIsSubSection()) { $standardColumnNames[] = 'sub_section_ids'; } $standardColumnNames[] = 'responsible_user_ids'; $standardColumnNames[] = 'risk_owner_id'; $this->headerMappings = []; foreach ($standardColumnNames as $index =>$standardColumnName) { foreach(Language::all() as $language) { $this->headerMappings[$index][$standardColumnName][] = Str::slug(__("labels.{$standardColumnName}", [], $language->code), '_'); } } } private function mapHeaderRow(BeforeImport $event) { $this->getHeaderMappings(); $worksheet = $event->getDelegate()->getActiveSheet(); $headerRow = $worksheet->getRowIterator(1)->current()->getCellIterator(); foreach ($headerRow as $cell) { $headerValue = Str::slug($cell->getValue(), "_"); // $columnLetter = $cell->getColumn(); // Convert letter index to numerical index (0, 1, 2, ...) $columnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($columnLetter) - 1; if (!isset($this->headerMappings[$columnIndex])) { break; } // Find the correct key in header mappings $header = $this->headerMappings[$columnIndex]; foreach($header as $expectedHeader => $aliases) { if (in_array($headerValue, $aliases)) { $cell->setValue($expectedHeader); // Set the cell to the standard header break; } } } } } Can anyone edit this code and share it Share Improve this question edited Mar 26 at 6:03 Rahul Rahul asked Mar 25 at 11:05 Rahul RahulRahul Rahul 12 bronze badges 4
  • Only issue is that if you use PHP/Laravel to validate the date, 31-02-2025 is actually a valid date; Carbon\Carbon::parse('31-02-2025') returns 2025-03-03. That being said; what have you tried? Where are you stuck? Please edit your question and include your code – Tim Lewis Commented Mar 25 at 14:17
  • Carbon::parse will correct your date , but if you don't want to insert wrong date data in database , then you can create custom validation. – Alimon Karim Commented Mar 25 at 14:26
  • I'm curious about how to escape from the Staging Ground. Please update your code block – Abdulla Nilam Commented Mar 26 at 6:57
  • That's a lot of code for a simple date validation. Also, are you sure your problem is directly related to Excel itself? Finally, Laravel 7 is EOL since four years - please update your application to ensure that you're not facing any problem that was resolved in the meantime – Nico Haase Commented Mar 27 at 12:34
Add a comment  | 

2 Answers 2

Reset to default 1

You can use the date validation rule for that (Docs).

Tried this laravel playground and the following code worked:

<?php

$date = '2025-02-31';

$rules = [
    'date' => 'date',
];
$validator = \Validator::make(['date' => $date], $rules);

if ($validator->fails()) {
  dump('Invalid date');
    // Throw exception / log error / store faulty line...
}

$date = '2025-02-25';

$rules = [
    'date' => 'date',
];
$validator = \Validator::make(['date' => $date], $rules);

if ($validator->fails()) {
  dump('Invalid date 2');
    // Throw exception / log error / store faulty line...
}

You can basically use the Validator facade wherever you want, with a given set of rules, just like you would do it in a Request.

Use built in php function checkdate()

<?php
$date = explode('-','31-02-2025');
vardump(checkdate($date[1],$date[0],$date[2]);
/* bool(false) */

vardump(checkdate(2,28,2025));
/* 28-02-2025 => bool(true) */

本文标签: phpHow to Validate Imported Dates in Excel to Check for Invalid or NonExistent DatesStack Overflow