Laravel Livewire Add or Remove Dynamically Input Fields
In this tutorial, we will create simple add remove dynamic textbox example using laravel livewire. you can use laravel livewire with laravel 6, laravel 7 and laravel 8 version.
Install Laravel 8
first of all we need to get fresh Laravel 8 version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Create Model and Migration
php artisan make:model Contact -m
App/Http/Models/Contacts.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
protected $fillable = [
'name', 'phone'
];
}
database/migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContactcTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('phone');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contacts');
}
}
Install Livewire
now in this step, we will simply install livewire to our laravel 8 application using bellow command:
composer require livewire/livewire
Create Component
Now here we will create livewire component using their command. so run bellow command to create add more component.
php artisan make:livewire contacts
Now they created fies on both path:
app/Http/Livewire/Contacts.php
resources/views/livewire/contacts.blade.php
Now both file we will update as bellow for our contact us form.
app/Http/Livewire/Contacts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Contact;
use App\Http\Livewire\Field;
use Illuminate\Http\Request;
class Contacts extends Component
{
public $contacts, $name, $phone, $contact_id;
public $updateMode = false;
public $inputs = [];
public $i = 1;
/**
* Write code on Method
*
* @return response()
*/
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->inputs ,$i);
}
/**
* Write code on Method
*
* @return response()
*/
public function remove($i)
{
unset($this->inputs[$i]);
}
/**
* Write code on Method
*
* @return response()
*/
public function render()
{
$this->contacts = Contact::all();
return view('livewire.contacts');
}
/**
* Write code on Method
*
* @return response()
*/
private function resetInputFields(){
$this->name = '';
$this->phone = '';
}
/**
* Write code on Method
*
* @return response()
*/
public function store()
{
$validatedDate = $this->validate([
'name.0' => 'required',
'phone.0' => 'required',
'name.*' => 'required',
'phone.*' => 'required',
],
[
'name.0.required' => 'name field is required',
'phone.0.required' => 'phone field is required',
'name.*.required' => 'name field is required',
'phone.*.required' => 'phone field is required',
]
);
foreach ($this->name as $key => $value) {
Contact::create(['name' => $this->name[$key], 'phone' => $this->phone[$key]]);
}
$this->inputs = [];
$this->resetInputFields();
session()->flash('message', 'Contact Has Been Created Successfully.');
}
}
resources/views/livewire/contacts.blade.php
<div>
@if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
@endif
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
</tr>
@foreach($contacts as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->phone }}</td>
</tr>
@endforeach
</table>
<form>
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
@error('name.0') <span class="text-danger error">{{ $message }}</span>@enderror
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="phone" class="form-control" wire:model="phone.0" placeholder="Enter Phone">
@error('phone.0') <span class="text-danger error">{{ $message }}</span>@enderror
</div>
</div>
<div class="col-md-2">
<button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
</div>
</div>
</div>
@foreach($inputs as $key => $value)
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
@error('name.'.$value) <span class="text-danger error">{{ $message }}</span>@enderror
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" wire:model="phone.{{ $value }}" placeholder="Enter phone">
@error('phone.'.$value) <span class="text-danger error">{{ $message }}</span>@enderror
</div>
</div>
<div class="col-md-2">
<button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">Remove</button>
</div>
</div>
</div>
@endforeach
<div class="row">
<div class="col-md-12">
<button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Submit</button>
</div>
</div>
</form>
</div>
Create Route
now we will create one route for calling our example, so let's add new route to web.php file as bellow:
routes/web.php
Route::get('contacts', function () {
return view('default');
});
Create View File
here, we will create blade file for call form route. in this file we will use @livewireStyles, @livewireScripts and @livewire('contact-form'). so let's add it.
resources/views/default.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Livewire Example - ItSolutionStuff.com</title>
@livewireStyles
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="card">
<div class="card-header">
Laravel Livewire Example - ItSolutionStuff.com
</div>
<div class="card-body">
@livewire('contacts')
</div>
</div>
</div>
</body>
@livewireScripts
</html>
Now you can run using bellow command:
php artisan serve
Open bellow URL:
localhost:8000/contacts
No comments