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'); }}
Thank you for tutorial. Would be nice to see "real-time" validation example with a good UI/UX.
A few Livewire validation examples are in this latest course: https://laraveldaily.com/lesson/livewire-order-management-system/create-new-category-modal
tanks
thank's a lot
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