Currently, our form doesn't have any validation after submitting, so let's add a few rules.
Validation Before Submit
The most straightforward way is just to call $this->validate()
with validation rules as a parameter in a typical Laravel syntax. And yes, all the same Laravel validation rules can be used.
public function save(): void{ $this->validate([ 'name' => 'required|min:3', ]); Company::create([ 'name' => $this->name, 'country_id' => $this->country, 'city_id' => $this->city, ]);
Now, let's show the validation errors in the Livewire Blade file. Again, the syntax of the @error
directive is the same as you would do it in the default Laravel. That's another proof that Livewire is excellent if you want to stay within the "comfort zone" of Laravel instead of learning new JS syntax.
resources/views/livewire/company-create.blade.php
<form wire:submit="save"> <div class="mb-4"> <label for="name" class="block text-gray-700">Company name</label> <input wire:model="name" type="text" required id="name" class="w-full p-2 mt-1 border rounded border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"> @error('name') <span class="mt-2 text-sm text-red-600">{{ $message }}</span> @enderror </div>
As a result, if we click Submit, we see this:
Validation with Attributes
Another way to add the rules is to use PHP 8 syntax of attributes on top of each property variable.
Then, you don't need to pass any...