How to use Form Request in Livewire

By default, Livewire doesn’t allow to use of Form Request classes for validation. But, as with many things, there is a workaround.

Quote from Livewire Docs: You might be wondering if you can use Laravel's "FormRequest"s. Due to the nature of Livewire, hooking into the HTTP request wouldn't make sense. For now, this functionality is not possible or recommended.


Let's say we have a Post Model with two fields title and body. Both fields need to be required and string. In your Form Request add the rules:

class PostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'string'],
'body' => ['required', 'string'],
];
}
 
public function authorize(): bool
{
return true;
}
}

In Livewire Component you can add rules in the rules() method by returning an array. In this method, you can return the rules() method from your Form Request. Just don't forget that public properties in Livewire Component need to be the same name as in the rules.

In your component:

class PostForm extends Component
{
public string $title;
public string $body;
 
protected function rules(): array
{
return (new PostRequest())->rules();
}
 
public function render(): View
{
return view('livewire.post-form');
}
}

Now as usual before saving you can validate the form.

class PostForm extends Component
{
public string $title;
public string $body;
 
public function save()
{
$this->validate();
// ...
}
 
protected function rules(): array
{
return (new PostRequest())->rules();
}
 
public function render(): View
{
return view('livewire.post-form');
}
}

form request in livewire component

avatar

Thank you for tutorial. Would be nice to see "real-time" validation example with a good UI/UX.

avatar

A few Livewire validation examples are in this latest course: https://laraveldaily.com/lesson/livewire-order-management-system/create-new-category-modal

👍 1
avatar
سجاد اسکندریان

tanks

avatar

thank's a lot

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials