To address the issue of the unique constraint error and improve the logic of your Livewire components, let's break down the solution into a few steps:
-
Ensure Proper Validation and Uniqueness Check: Make sure that the uniqueness check for the
emailfield is correctly applied to the specific table related to thebusiness_infoabletype. -
Avoid Duplicate Submissions: Ensure that the form submission logic is not being triggered multiple times, which could lead to duplicate entries.
-
Refactor the Code for Clarity: Simplify the logic to make it easier to follow and maintain.
Here's a revised approach:
Step 1: Update the CreateCompany Component
Ensure that the validateTaxId method only sets the flag to show the business info form and does not attempt to save any data prematurely.
public function validateTaxId()
{
$this->validate();
// Check uniqueness
if (Company::where('tax_id', $this->tax_id)->exists()) {
$this->addError('tax_id', 'This company already exists.');
return;
}
// Show the business info form if validation and uniqueness check pass
$this->showBusinessInfoForm = true;
}
Step 2: Update the CreateBusinessInfo Component
Ensure that the saveBusinessInfo method only dispatches the event and does not attempt to save the BusinessInfo model directly. The actual saving should be handled in the CreateCompany component.
public function saveBusinessInfo()
{
$this->validate();
// Dispatch event to notify that the business info is validated
$this->emit('businessInfoValidated', $this->getData());
// Flash a success message
session()->flash('message', 'Business info validated successfully.');
// Reset the form
$this->resetForm();
}
Step 3: Handle the Business Info in CreateCompany
In the CreateCompany component, handle the saving of both the Company and BusinessInfo models after the business info is validated.
public function saveCompanyWithBusinessInfo(array $businessInfoData)
{
try {
// Ensure that tax_id is set before saving the company
if (empty($this->tax_id)) {
$this->addError('tax_id', 'Tax ID is required.');
return;
}
// Create the company
$company = Company::create([
'tax_id' => $this->tax_id,
]);
// Save the business info
$company->businessInfo()->create($businessInfoData);
// Attach the current user as an admin and set it as the current company
auth()->user()->companies()->attach($company->id, ['role' => 'admin']);
auth()->user()->update(['current_company_id' => $company->id]);
// Show success toast
Flux::toast(
duration: 2000,
variant: 'success',
heading: 'Company Created!',
text: 'Company and business information saved successfully.'
);
// Redirect to the company's dashboard
return redirect()->route('companies.show', $company->id);
} catch (\Exception $e) {
Log::error('Error saving company: '.$e->getMessage());
$this->addError('exception', 'An error occurred while saving the company.');
}
}
Step 4: Blade Template Adjustments
Ensure that the form submission is correctly wired to the validateTaxId method and that the business info form is only shown when the flag is set.
<div>
<x-form-section submit="validateTaxId">
<x-slot name="title">
{{ __('Company Details') }}
</x-slot>
<x-slot name="description">
{{ __('Create a new company to start your new project.') }}
</x-slot>
<x-slot name="form">
<div class="col-span-6 sm:col-span-4">
<flux:input mask="9999999999" wire:model.defer="tax_id" label="{{ __('Company Tax ID') }}" type="text"
placeholder="10 digit tax ID" required badge="*" autofocus badge="*" required
invalid="{{ $errors->has('tax_id') }}" />
</div>
</x-slot>
<x-slot name="actions">
<div class="flex items-center justify-between">
<x-validation-errors class="flex flex-col alert alert-danger" />
<flux:spacer />
<flux:button variant="primary" type="submit">
{{ __('Check') }}
</flux:button>
</div>
</x-slot>
</x-form-section>
@if ($showBusinessInfoForm)
<flux:separator class="my-6" />
@livewire('create-business-info', [
'business_infoable' => $company
])
@endif
</div>
By following these steps, you should be able to resolve the unique constraint error and streamline the form submission process.