In this tutorial, I’ll show you how to bind form inputs using wire:model in Laravel 11 with Livewire 3. Livewire makes it easy to handle real-time form updates without writing JavaScript. By binding inputs directly to component properties, we can update data instantly and improve the user experience.
Livewire makes it easy to handle real-time input updates and validation without writing complex JavaScript. We’ll go through a step-by-step example to see how wire:model
works in a Livewire component.
Laravel 11 Livewire 3 wire:model - Bind Form Input
If you haven’t installed Livewire yet, you can do so using Composer:
composer require livewire/livewire
Run the following command to generate a new Livewire component:
php artisan make:livewire UserForm
This will create two files:
app/Livewire/UserForm.php
(Component class)
resources/views/livewire/user-form.blade.php
(View file)
Edit app/Livewire/UserForm.php to add properties and a save method:
namespace App\Livewire;
use Livewire\Component;
class UserForm extends Component
{
public string $name = '';
public string $email = '';
public function save()
{
// Perform validation (optional)
$this->validate([
'name' => 'required|min:3',
'email' => 'required|email',
]);
// Process form submission (e.g., save to database)
session()->flash('message', 'Form submitted successfully!');
}
public function render()
{
return view('livewire.user-form');
}
}
Edit resources/views/livewire/user-form.blade.php
to bind inputs:
<div>
<form wire:submit.prevent="save">
<div>
<label for="name">Name:</label>
<input type="text" id="name" wire:model="name" class="border p-2 w-full">
</div>
<div class="mt-2">
<label for="email">Email:</label>
<input type="email" id="email" wire:model="email" class="border p-2 w-full">
</div>
<button type="submit" class="mt-4 bg-blue-500 text-white px-4 py-2">Submit</button>
</form>
@if (session()->has('message'))
<p class="mt-2 text-green-500">{{ session('message') }}</p>
@endif
</div>
Include Livewire scripts in resources/views/layouts/app.blade.php
or your main layout:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Livewire Form</title>
@livewireStyles
</head>
<body>
<livewire:user-form />
@livewireScripts
</body>
</html>
Run the laravel application using the following command.
php artisan serve
You might also like:
In this post i will show you how to implement bootstrap datetimepicker with example, bootstrap 4 datetimepicke...
Apr-02-2021
In this post we will see how to upload image in summernote editor. there are many editor available in laravel...
Jul-09-2021
Today, In this post we will see how to use json field in mysql database. In this tutorial i will give mysql json data ty...
Jun-04-2021
In this article, we will see how to create pagination using jquery. We will create jquery pagination using mul...
Nov-08-2022