Laravel Livewire - Dynamically Add or Remove input fields

Admin   Laravel   504  2021-03-15 18:30:05

Hi Dev,

Today, I am going to share with you how to add or remove input fields using livewire in laravel application. i also implemented dynamically generate input fileds validation. So if you have to add dynamically more than one fields with laravel livewire.

You can add more input fields in laravel livewire. laravel livewire add more input field dynamically. We will show dynamically add or remove input field laravel livewire.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communicaton.

Here i will give you full example for dynamically add or remove input fields in laravel livewire. So let's follow the bellow step by step.

Step 1 : Install Laravel App

In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

 

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

 

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=Enter_Your_Database_Name

DB_USERNAME=Enter_Your_Database_Username

DB_PASSWORD=Enter_Your_Database_Password

Step 3 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

 

composer require livewire/livewire

Step 4 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create user form component:

 

php artisan make:livewire users

Now they created fies on both path:

 

app/Http/Livewire/Users.php

resources/views/livewire/users.blade.php

Now first file we will update as bellow for Users.php file.

app/Http/Livewire/Users.php

 

<?php

namespace App\Http\Livewire;

use Livewire\Component;

use App\User;

use App\Http\Livewire\Field;

use Illuminate\Http\Request;

class Users extends Component

{

public $users, $name, $email, $user_id;

public $updateMode = false;

public $inputs = [];

public $i = 1;

public function add($i)

{

$i = $i + 1;

$this->i = $i;

array_push($this->inputs ,$i);

}

public function remove($i)

{

unset($this->inputs[$i]);

}

public function render()

{

$this->users = User::all();

return view('livewire.users');

}

private function resetInputFields(){

$this->name = '';

$this->email = '';

}

public function store()

{

$validatedDate = $this->validate([

'name.0' => 'required',

'email.0' => 'required',

'name.*' => 'required',

'email.*' => 'required|email',

],

[

'name.0.required' => 'name field is required',

'email.0.required' => 'email field is required',

'email.0.email' => 'The email must be a valid email address.',

'name.*.required' => 'name field is required',

'email.*.required' => 'email field is required',

'email.*.email' => 'The email must be a valid email address.',

]

);

foreach ($this->name as $key => $value) {

User::create(['name' => $this->name[$key], 'email' => $this->email[$key]]);

}

$this->inputs = [];

$this->resetInputFields();

session()->flash('message', 'Users Created Successfully.');

}

}

Step 5 : Add Route

now, we need to add route for image form in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php

 

Route::view('users','livewire.home');

Step 6 : Create View

Here, we will create blade file for call crud opertaion route. in this file we will use @livewireStyles, @livewireScripts and @livewire('users'). so let's add it.

resources/views/livewire/users.blade.php

 

<div>

@if (session()->has('message'))

<div class="alert alert-success">

{{ session('message') }}

</div>

@endif

<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="email" class="form-control" wire:model="email.0" placeholder="Enter Email">

@error('email.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="email" class="form-control" wire:model="email.{{ $value }}" placeholder="Enter Email">

@error('email.'.$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">Save</button>

</div>

</div>

</form>

</div>

resources/views/livewire/home.blade.php

 

<!DOCTYPE html>

<html>

<head>

<title></title>

<script src="{{ asset('js/app.js') }}" defer></script>

<link href="{{ asset('css/app.css') }}" rel="stylesheet">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

@livewireStyles

</head>

<body>

<div class="container">

<div class="row mt-5 justify-content-center">

<div class="mt-5 col-md-8">

<div class="card">

<div class="card-header bg-success text-white"><h5 style="font-size: 19px;">Laravel Livewire - Dynamically Add or Remove input fields - NiceSnippets.com</h5></div>

<div class="card-body">

@if (session()->has('message'))

<div class="alert alert-success">

{{ session('message') }}

</div>

@endif

@livewire('users')

</div>

</div>

</div>

</div>

</div>

@livewireScripts

</script>

</body>

</html>

Now we are ready to run our example so run bellow command for quick run:

 

php artisan serve

Now you can open bellow URL on your browser:

 

http://localhost:8000/users

It will help you..

Preview