Laravel Livewire Add or Remove Dynamically Input Fields Example

By Hardik Savani April 16, 2024 Category : Laravel

Here, i will show you how to works laravel livewire add more dynamically input fields. i explained simply about laravel livewire add or remove dynamically input fields. This tutorial will give you simple example of laravel livewire add more input fields example. i would like to share with you add remove dynamic textbox laravel livewire.

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, laravel 8, laravel 9, laravel 10 and laravel 11 version.

Livewire is a full-stack framework for Laravel framework that makes building dynamic interfaces simple, without leaving the comfort of Laravel. if you are using livewire with laravel then you don't worry about writing jquery ajax code, livewire will help to write very simple way jquery ajax code using php. without page refresh laravel validation will works, form will submit etc.

Here, i will give you very simple example to contacts table with name and phone number and i will store that data to database without refresh page in single form. we will use only livewire/livewire package.

So, let's follow bellow step and you will get bellow layout:

Step 1 : 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

Step 2 : Create Migration and Model

Here, we need create database migration for files table and also we will create model for files table.

php artisan make:migration create_contacts_table

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');

}

}

php artisan migrate

now we will create Contact model by using following command:

php artisan make:model Contact

App/Models/Contact.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'

];

}

Step 3: Install Livewire

now in this step, we will simply install livewire to our laravel 8 application using bellow command:

composer require livewire/livewire

Step 4: 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/file-upload.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>

Step 5: 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');

});

Step 6: 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

I hope it can help you...

Tags :
Shares