Skip to main content

Form Validation: Multiple Options

Premium
4:33

Text Version of the Lesson

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

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

S
Smash ✓ Link copied!
M
Modestas ✓ Link copied!

Updated, thank you for letting us know!

M
mfiazahmad ✓ Link copied!

What about Laravel form requests instead of this Validate attribute?

M
Modestas ✓ Link copied!

Could you expand on your question? But in short:

Nobody is stopping you from using the Laravel form requests, but that will do a full page reload and you'll have to build another controller for it.

SA
Stephan Apenbrink ✓ Link copied!

Hi, in the app/Livewire/CompanyCreate.php: it should be "class CompanyCreate extends Component" instead of "class CreatePost extends Component"

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.