How to Create an Input Form or Dynamic Input Field with Laravel 8 and Livewire

How to Create an Input Form or Dynamic Input Field with Laravel 8 and Livewire

Admin
Admin・ 17 Agustus 2021
11 min read ・ 20492 views
Series: Laravel Livewire

Dynamic Input Form Laravel Livewire - In this article I will share a tutorial on how to create dynamic forms or input fields using laravel version 8 and livewire. The dynamic form feature or input fields is usually used to input unlimited data such as user contacts, social account links and others.

dynamic input fields laravel livewire

If you have a facebook page, maybe you've seen add other account features like the example picture above. In the Facebook page feature, we can freely add our official accounts in addition to Facebook pages such as Instagram, Twitter, GitHub and others.

Well, in this tutorial, I will try to explain how to create a feature like on the facebook page, namely adding another account with dynamic forms or input fields using laravel version 8 and livewire.

Ok, let's get straight to the code.

Step 1: Install Laravel Latest Version

laravel new dynamic-form-laravel-livewire

 

The first step in this tutorial is that we start by installing the latest Laravel (currently version 8). To install laravel, we can use the laravel installer command as above or we can also install laravel with composer like the command below.

composer create-project laravel/laravel dynamic-form-laravel-livewire

With this command, we will install laravel with the name of the folder or project, namely dynamic-form-laravel-livewire. If the installation process is complete, don't forget to enter the project with cd dynamic-form-laravel-livewire.

Step 2: Create Database & Setup .ENV

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dynamic-form-laravel-livewire
DB_USERNAME=root
DB_PASSWORD=

After completing the Laravel installation, the next step is to create a new database that will be used to store the account data that we will create in this tutorial. Please create a new database and don't forget to adjust the DB_DATABASE in the .env file.

Step 3: Create Model & Migration File

 php artisan make:model Account -m

Create account model and migration files by running the command as above. With this command, it will automatically generate two files contained in app/Models/Account and database/migrations/[timestamp]_create_accounts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->string('account');
            $table->string('username');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('accounts');
    }
} 

 

Open the newly generated accounts migration file. Then add the account and username fields in the up method, so that the overall migration file will be like the code above.

php artisan migrate

Run the php artisan migrate command to migrate all files in the migrations folder to the database we just created in step 2.

Don't forget to add protected $guarded = []; in the /app/Models/Account.php file.

Step 4: Install Livewire

composer require livewire/livewire

After installing laravel and creating a database, we continue by installing livewire in our laravel project. Run the command as above to install livewire.

Step 5: Generate Livewire Components

php artisan make:livewire UserAccount

Then we need to create or generate livewire components which we will use to display the data accounts and create dynamic forms or input fields along with the post (store) action. Run the command as above to generate livewire components. This command will generate livewire components located in the directory;

app/Http/Livewire/UserAccount.php
resources/views/livewire/user-account.blade.php

Step 6: Setup UserAccount.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Http\Request;
use App\Models\Account;

class UserAccount extends Component
{
    public $accounts, $account, $username, $account_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]);
    }

    private function resetInputFields(){
        $this->account = '';
        $this->username = '';
    }

    public function store()
    {
        $validatedDate = $this->validate([
                'account.0' => 'required',
                'username.0' => 'required',
                'account.*' => 'required',
                'username.*' => 'required',
            ],
            [
                'account.0.required' => 'Account field is required',
                'username.0.required' => 'Username field is required',
                'account.*.required' => 'Account field is required',
                'username.*.required' => 'Username field is required',
            ]
        );
   
        foreach ($this->account as $key => $value) {
            Account::create(['account' => $this->account[$key], 'username' => $this->username[$key]]);
        }
  
        $this->inputs = [];
   
        $this->resetInputFields();
   
        session()->flash('message', 'Account Added Successfully.');
    }

    public function render()
    {
        $data = Account::all();
        return view('livewire.user-account',['data' => $data]);
    }
} 

Open the UserAction.php file that we generated in the previous step, then adjust the existing code with the code as above. In the code, we create several methods such as add (to add an input form or input field), remove (to delete an input form or input field), resetInputFields (assigned to empty the input form or input field after the save or store process), store ( to add data to database or accounts table) and render (to display account data in user-account.blade.php view file).

Step 7: Setup Blade View

Almost complete. In this step 7 we need to setup two blade views namely welcome.blade.php and livewire/user-account.blade.php.

Edit welcome.blade.php

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
        <title>How to Create Dynamic Forms with Laravel 8 and Livewire</title>
        @livewireStyles
    </head>
    <body>
        @livewire('user-account')
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        @livewireScripts
    </body>
</html>

Open the welcome.blade.php file, then update it like the code above. In this welcome.blade.php file, we add @livewireStyles, @livewire('user-account') and @livewireScripts.

Edit livewire/user-account.blade.php

<div class="container">
    <div class="row mt-5">
         <h1 class="fs-5 text-center">Dynamic Form with Laravel 8 & Livewire</h1>
    </div>
    <div class="row justify-content-center">
        <div class="w-50">
            <div class="card my-3">
                <div class="card-body">
                    <form class="row g-3 justify-content-center">
                        <div class="col-4">
                            <label class="visually-hidden">Account</label>
                            <select class="form-select" aria-label="Default select example" wire:model="account.0">
                                <option selected>Account</option>
                                <option value="facebook">Facebook</option>
                                <option value="instagram">Instagram</option>
                                <option value="twitter">Twitter</option>
                                <option value="github">Github</option>
                            </select>
                            @error('account.0') <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                        <div class="col-6">
                            <label class="visually-hidden">Username</label>
                            <input type="text" class="form-control" wire:model="username.0" placeholder="Your Username">
                            @error('username.0') <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                        <div class="col-2">
                            <button class="btn btn-primary mb-3" wire:click.prevent="add({{$i}})"><i class="bi bi-plus"></i></button>
                        </div>
                        {{-- Add Form --}}
                        @foreach ($inputs as $key => $value)
                        <div class="col-4">
                            <label class="visually-hidden">Account</label>
                            <select class="form-select" aria-label="Default select example" wire:model="account.{{ $value }}">
                                <option selected>Account</option>
                                <option value="facebook">Facebook</option>
                                <option value="instagram">Instagram</option>
                                <option value="twitter">Twitter</option>
                                <option value="github">Github</option>
                            </select>
                            @error('account.') <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                        <div class="col-6">
                            <label class="visually-hidden">Username</label>
                            <input type="text" class="form-control" wire:model="username.{{ $value }}" placeholder="Your Username">
                            @error('username.') <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                        <div class="col-2">
                            <button class="btn btn-light mb-3" wire:click.prevent="remove({{$key}})"><i class="bi bi-x"></i></button>
                        </div>
                        @endforeach
                        <div class="row">
                            <div class="col-12 ps-0">
                                 <button type="button" class="btn btn-primary" wire:click.prevent="store()">Save</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            @if (session()->has('message'))
                <div class="alert alert-success">
                {{ session('message') }}
                </div>
            @endif
            <table class="table table-responsive">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Account</th>
                        <th scope="col">Username</th>
                    </tr>
                </thead>
                <tbody>
                    @php
                    $no = 0;
                    @endphp
                    @foreach ($data as $data)
                    <tr>
                        <th scope="row">{{ ++$no }}</th>
                        <td>{{ $data->account }}</td>
                        <td>{{ $data->username }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

Then open the livewire/user-account file that we generated in step 5. Update all the code in the file with all the code as above. With the code as above, we create a dynamic form input or input fields and create a table view that serves to display the account data that has been successfully added (store).

Step 8: Testing

dynamic form with laravel 8 & livewire

After going through the processes starting from installing the latest version of laravel, database setup, installing and generating livewire components to the blade view setup process, now we have arrived at the last step which is testing dynamic forms or input fields that we have created with laravel 8 and livewire.

Please run your laravel project server with the command php artisan serve, then open it in a browser with URL 127.0.0.1:8000 or dynamic-form-laravel-livewire.test. Then please try to fill in the data in the input field and click the + icon to add another input field, click the save button to add data to the database (store).

OK, so far we have succeeded in creating a dynamic form feature or input fields like the one on Facebook using laravel 8 and livewire. Good luck, hopefully this article can be useful and see you in the next article.

 

Credit: Online illustrations by Storyset

Tinggalkan Komentar
Loading Comments