Real time validation using Lifecycle hooks in Laravel Livewire.

In this article we will see how to do real time validation in Laravel Livewire projects using lifecycle hooks. Lifecycle hooks help you to run code at any part of the component’s lifecycle. You can also run the code before specific properties are being updated. Lifecycle hooks work like Single Page Application. 

Create Post Form Components.

First step is to create a livewire component. Use $rules for validation after creating public property. Then use another hook mount. After the component is instantiated and before render() is called mount runs.

Then you need to create a store method by passing $this->validate(); and save and rest. Final step is to create updated hooks.

 'required|min:8',
        'post.auther_number' => 'required|numeric|min:10',
        'post.description' => 'required|max:500',
    ];

    public function mount()
    {
        $this->post = $post ?? new Post();
    }

    public function storePost()
    {
        $this->validate();
 
        $this->post->save();

        $this->reset();
    }

    public function updated($name)
    {
        $this->validateOnly($name, [
            'post.title' => 'required|min:8',
            'post.auther_number' => 'required|numeric|min:10',
        ]);
    }

    public function render()
    {
        return view('livewire.post-form');
    }
}

Data Bind with Form- You have to create form and data bind using wire:model and call storepost method for save form. 

<div>

    <div class="container mx-auto">

        <form method="POST" wire:submit.prevent="storePost">

            @csrf

            <div>

                <label for="title">Title</label>

                <input type="text" wire:model.lazy="post.title"

                class="w-full py-2 rounded">

                @error('post.title')

                <span class="text-red-600">{{ $message }}</span>

                @enderror

            </div>

            <div class="mt-8">

                <label for="auther_number">Auther Number</label>

                <input type="text" wire:model.lazy="post.auther_number" 

                class="w-full py-2 rounded">

                @error('post.auther_number')

                <span class="text-red-600">{{ $message }}</span>

                @enderror

            </div>

            <div class="mt-8">

                <label class="block mb-2 text-xl">Description </label>

                <textarea wire:model.lazy="post.description" rows="3" cols="20" 

                class="w-full rounded">

            </textarea>

                @error('post.description')

                <span class="text-red-600">{{ $message }}</span>

                @enderror

            </div>

            <button type="submit" 

                    class="px-4 py-2 mt-4 text-sm text-white bg-blue-600 rounded-lg hover:bg-blue-700">

                Submit

            </button>

        </form>

    </div>

</div>