You don't need Laravel Precognition if you are using Livewire

By: Roel
July 18, 2024

You don't need Laravel Precognition if you are using Livewire. You can do "live validation" with Livewire that feels like SPA. You only write the validation once and that is thru the component class. 

Precognition are more targetted for those who use Javascript frameworks so they don't have to write validation logic twice ( one in backend and another one in back-end)

Here's the steps:

1. Create the Livewire Component

First, create a new Livewire component. For this example, let's call it UserForm.

php artisan make:livewire UserForm

2. Define the Component

Edit the UserForm component class to include validation logic.

// app/Http/Livewire/UserForm.php

namespace App\Http\Livewire;

use Livewire\Component;

class UserForm extends Component
{
    public $name;
    public $email;

    protected $rules = [
        'name' => 'required|min:3',
        'email' => 'required|email',
    ];

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

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

3. Create the Component View

Create a view for the component.

<!-- resources/views/livewire/user-form.blade.php -->

<div>
    <form wire:submit.prevent="submit">
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" wire:model="name">
            @error('name') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <label for="email">Email:</label>
            <input type="text" id="email" wire:model="email">
            @error('email') <span class="error">{{ $message }}</span> @enderror
        </div>

        <button type="submit">Submit</button>
    </form>
</div>


Explanation

  1. Component Class:
    • public $name, public $email: The properties to hold form input values.
    • protected $rules: Validation rules for the inputs.
    • updated($propertyName): The Livewire lifecycle hook that triggers validation whenever an input property is updated.
  2. Component View:
    • wire:model="name", wire:model="email": Bind the input fields to the component properties.
    • @error('name'), @error('email'): Display validation error messages.


This setup will display validation errors live, without needing to submit the form or refresh the page.

In here the updated method from the Livewire component class will be responsible for live validation as the user types

Tags:

About the Author

Roel
Roel

Hi, my name is Roel. I am a TALL stack developer. I created this site to document all web applications I created using the TALL stack. I exclusively built products using Laravel because I like the experience writing applications using the simplest framework/stack available.



Please login to comment.

© 2024 Talldevelopers.com, All rights reserved.