jmacdiarmid's avatar

Using Custom Form Request with Livewire v2

I created a form request since I need to customize the field validation messages and passing it to my store method. When opening my modal create form and attempt to submit an empty form, I can see that it's picking up the custom error messages for each field. However, when I try to submit a form with valid data I get the following exception error. How do I use Form Requests with Livewire?

Livewire\Exceptions\MissingRulesException
Missing [$rules/rules()] property/method on Livewire component: [admin.campaign-packages].

Here is my form request:

    public function authorize()
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'title'                 			=> 'required|string',
            'duration_id'           => 'required|numeric|min:0|not_in:0',
            'monthly_impressions'   => 'required',
            'monthly_investment'    => 'required',
            'price'                 => 'required',
        ];
    }

    public function messages(): array
    {
        return [
            'duration_id.required'  => 'The Commitment Length field is required',
        ];
    }

0 likes
7 replies
martinbean's avatar

@jmacdiarmid You don’t use form requests with Livewire components; Livewire handles the lifecycle itself so any validation should be in the component itself as per the error message.

jmacdiarmid's avatar

Ok. I got it working. Thank you. It took me a little bit to wrap my head around what I was reading in the Livewire docs. It looks like my issue was more related to the $validationAttributes array than the custom messages. I also had to remove related variables from the validatedOnly() in the updated method as well the validate() call in the store method.

johnef_sh's avatar

@okiaso Hi dear I like ur solution very much but how the new StoreRoleRequest() looks like from inside?

okiaso's avatar
<?php

namespace App\Http\Livewire\Role\System;

use App\Http\Requests\StoreRoleRequest;
use Livewire\Component;

class Edit extends Component
{
    public $item; // role
    public $name; // form inpute: name

    public function render()
    {
        return view('livewire.role.system.edit');
    }

    public function mount()
    {
        // Processing the form with RoleController::update, not Livewire
        $this->name = $this->item->name;
    }

    // Reuse external "Form Request Validation"
    protected function rules()
    {
        $request = new StoreRoleRequest();

        return $request->rules();
    }

    protected function updated()
    {
        $this->validate();
    }
}
3 likes

Please or to participate in this conversation.