Handling form inputs in Livewire can be streamlined and efficient if you follow best practices. Let's address your questions one by one:
-
What needs to be computed?
Computed properties in Livewire are used to derive data that depends on other properties. They are similar to computed properties in Vue.js. In your case, the
eventPackagemethod is a good candidate for a computed property because it derives its value based on the$slugproperty. This means whenever$slugchanges, theeventPackagewill automatically update.#[Computed] public function getEventPackageProperty() { return \App\Models\EventPackage::with('items') ->where('slug', $this->slug) ->firstOrFail(); }Note: Use the
getPropertyNamePropertynaming convention for computed properties. -
What needs to be locked?
Locked properties are used when you want to ensure that a property is not updated by the client-side. This is useful for properties that should remain constant during the component's lifecycle. If you have properties that should not be changed by the user, consider using locked properties.
-
Do I need to declare every form input as a variable in the component?
Yes, in Livewire, each form input that you want to bind to must be declared as a public property in your component. This is how Livewire tracks changes and updates the component state. However, if you have a large number of form fields, you can consider grouping them into an array to make your component cleaner:
public $form = [ 'email' => '', 'name' => '', 'phone' => '', 'address' => '', 'complement' => '', 'neighborhood' => '', 'city' => '', 'state' => '', 'zip_code' => '', 'church_name' => '', 'gender' => '', 'document_cpf' => '', 'birthday' => '', 'group_level_id' => '', 'over_18' => false, ];Then, you can update your validation rules to match this structure:
public function rules(): array { return [ 'form.email' => 'required|email', 'form.name' => 'required|min:8', 'form.phone' => 'required|min:10', 'form.address' => 'required|min:3', 'form.complement' => 'nullable|min:3', 'form.neighborhood' => 'required|min:3', 'form.city' => 'required|min:3', 'form.state' => 'required|min:2', 'form.zip_code' => 'required|min:5', 'form.church_name' => 'required|min:3', 'form.gender' => 'required|numeric', 'form.document_cpf' => 'required|min:3', 'form.birthday' => 'required|date|min:3', 'form.over_18' => 'nullable|boolean', 'form.group_level_id' => 'required|numeric', ]; } -
Is this safe?
Livewire is designed to be secure by default. However, you should always validate and sanitize your inputs to prevent any potential security issues. Using the
rulesmethod for validation is a good practice. Additionally, ensure that any data manipulation or database operations are performed securely, using prepared statements or ORM methods to prevent SQL injection.
By following these guidelines, you can effectively manage form inputs in Livewire while keeping your code clean and maintainable.