Category: Laravel, Laravel

Testing validation rules in a Laravel Livewire component | C.S. Rhymes C.S. Rhymes HomeBooksNigel's Intranet AdventureHow NOT to make a WebsiteHow NOT to use a SmartphoneMy WorkThemesProjectsSitesStoriesSponsorsAboutBlogSponsorTesting validation rules in a Laravel Livewire componentPublished: May 25, 2021 by C.S. RhymesTesting validation rules can become quite tiresome pretty quickly if you have to write each test manually. For this example we have a form that allows a user to update their profile information with a Livewire ProfileForm component.In Livewire you can define validation rules by setting a rules array (shown below) and then validate using $this->validate().

Here are the rules we have set and the save() method that will validate the input.// App\Http\Livewire\ProfileForm.phpuseIlluminate\Validation\Rule;protectedfunctionrules(){return['user.id'=>'required','user.name'=>'required|max:200','user.email'=>['required','email',Rule::unique('users')->ignore($this->user->id)],'user.bio'=>'required|min:20|max:1000',];}publicfunctionsave(){$this->validate();// Save the user data$this->user->save();}So how can we go about testing each of these rules? There are 8 different validation rules in this simple example, but you don’t want to have to write 8 separate tests for each rule.

In our case we are passing in the field, the value and the rule./** * @test * @dataProvider validationRules **/publicfunctiontest_validation_rules($field,$value,$rule){}Testing the Livewire validation rulesNow we are ready to test the validation rules in the Livewire component.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners