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

muuucho's avatar
Level 11

Livewire: Adding ab element after validation

I like to add an element after validation, just before create():

       $this->validate();
			// Add (merge) ['team_id'  => Auth::User()->team_id]
       Company::create( $this->only('name', 'type_id', 'vat', 'gender'));

How do I code that?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To add an element to the data array after validation and before calling the create() method in Livewire, you can merge the additional data into the validated data array. Here's how you can do it:

  1. Validate the data.
  2. Merge the additional data (e.g., team_id from the authenticated user).
  3. Call the create() method with the merged data.

Here's the updated code:

public function createCompany()
{
    // Step 1: Validate the data
    $validatedData = $this->validate([
        'name' => 'required|string|max:255',
        'type_id' => 'required|integer',
        'vat' => 'required|string|max:255',
        'gender' => 'required|string|max:255',
    ]);

    // Step 2: Merge the additional data
    $validatedData = array_merge($validatedData, ['team_id' => Auth::user()->team_id]);

    // Step 3: Create the company with the merged data
    Company::create($validatedData);
}

In this example:

  • The validate() method validates the input data and returns an array of validated data.
  • The array_merge() function is used to add the team_id from the authenticated user to the validated data array.
  • Finally, the create() method is called with the merged data array to create a new Company record.

Make sure to adjust the validation rules according to your requirements. This approach ensures that the additional data is included in the array passed to the create() method.

1 like

Please or to participate in this conversation.