Skip to main content
Tutorial Free

How to use Form Request in Livewire

February 17, 2023
2 min read

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

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

L
Linas ✓ Link copied!

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

PK
Povilas Korop ✓ Link copied!

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

��
سجاد اسکندریان ✓ Link copied!

tanks

AK
ali karamniya ✓ Link copied!

thank's a lot

MA
Mahmoud Ahmed ✓ Link copied!

thanks What about if i want to access title value inside body to make specific custom validation in the same PostRequest class , in general when i dump request()->title i get null how to solve this

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.