Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

akaydin's avatar
Level 21

Livewire Conditional Form Submission

Hey,

I need help on a logic. I have a Company model. The companies table has only a single attribute, 'tax_id', which is unique for the companies. Once the user submits the first form with only tax_id input, I check the validity and uniqueness. If it's not unique, I display the "company already exists" error. (Next, I will list the existing company link there, but for now let's keep it simple)

If it's unique, we reveal the other form, business_infos. Since multiple models can have business information (customers, carriers, etc.) I have a trait, HasBusinessInfo. This form has a few attributes like "name, email, phone, tax_office, etc.". Company name and email are required. Email attribute is unique among this model's table, if it's a company form, then companies table, if carrier form then carriers table. I use getMorphClass() function.

Once the business info form is filled and submitted, we validate the inputs, then dispatch an event. I want to get these inputs in the first form, and handle the company creation there.

But I keep getting the unique constraint error, regarding email input. I believe it's because the component is trying to insert the same data twice. There must be a repeating command, which I could not figure out.

Also, I would like to have your help to simplify the code. Maybe you can offer a better way for the logic.

As a summary, I want to check the validity of the tax_id, if it's unique then I want to reveal the business info form, and only after then I want to save this new company.

Additionally, I have 3 extra functions. First, once the company created, I want this user to be assigned as an admin for this company. Second, I want to set this new company as the 'current_company' for this user. and lastly, I want to throw a Flux toast indicating that the company is succesfully created.

this is the second part of the form

and this is the create-company.blade.php

Thanks.

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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:

  1. Ensure Proper Validation and Uniqueness Check: Make sure that the uniqueness check for the email field is correctly applied to the specific table related to the business_infoable type.

  2. Avoid Duplicate Submissions: Ensure that the form submission logic is not being triggered multiple times, which could lead to duplicate entries.

  3. 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.

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.

By following these steps, you should be able to resolve the unique constraint error and streamline the form submission process.

akaydin's avatar
Level 21

Edit: Removed the saving business info fucntions. It was duplicating the saving action, so the second one was throwing the not unique error.

@LaryAI

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();
}

emit() is no longer available, instead there is dispatch() with v3.

If you remove all the functions, then how will we collect data from the form?

Please or to participate in this conversation.