Laravel 10 Livewire Form Tutorial


Laravel 10 livewire form example; In this tutorial, you will learn how to install laravel liveware package and as well as how to submit and store form data using the laravel livewire package in laravel web application.

Laravel Liveware Form Example Tutorial

Follow the below steps for creating and submit the form using laravel livewire package:

  • Step 1: Install Laravel
  • Step 2: Add Database Detail
  • Step 3: Generate Migration and Model by Command
  • Step 4: Install Livewire
  • Step 5: Create Component
  • Step 6: Create Route
  • Step 7: Create View File
  • Step 8: Run Development Server

Step 1: Install Laravel

First of all, Open your terminal OR command prompt and run following command for installing fresh laravel setup:

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

Step 2: Add Database Detail

Next, Add database credentials in the .env file. So open your project with any text editor and find .env file then add database detail here:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=here your database name here 
DB_USERNAME=here database username here 
DB_PASSWORD=here database password here

Step 3: Generate Model and Migration By Command

In this step, generate model and migration file using the following command:

php artisan make:model Contact-m

This command will create one model name Contact and also create one migration file for Contact table. After successfully run the command go to database/migrations file and put the below here :

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateContactsUsForms extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Next goto app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}

Next, Open your command prompt and run the following command to create the table into your database:

php artisan migrate

Next, Open App/Contact.php file and add the fillable properties:

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Contact extends Model
{
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'body',
    ];
}

Step 4: Install Livewire

In this step, install livewire to our laravel web application using the following command:

composer require livewire/livewire

Step 5: Create Component

In this step, create the livewire components using the following command. So Open your cmd and run the following command:

php artisan make:livewire contact-form

You can see a created file on the following path:

app/Http/Livewire/ContactForm.php
resources/views/livewire/contact-form.blade.php

Next, update the following code into your files, so follow the given path and update the code:

app/Http/Livewire/ContactForm.php

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use App\Contact;
  
class ContactForm extends Component
{
    public $name;
    public $email;
    public $body;
  
    public function submit()
    {
        $validatedData = $this->validate([
            'name' => 'required|min:6',
            'email' => 'required|email',
            'body' => 'required',
        ]);
  
        Contact::create($validatedData);
  
        return redirect()->to('/form');
    }
  
    public function render()
    {
        return view('livewire.contact-form');
    }
}

resources/views/livewire/contact-form.blade.php

<form wire:submit.prevent="submit">
    <div class="form-group">
        <label for="exampleInputName">Name</label>
        <input type="text" class="form-control" id="exampleInputName" placeholder="Enter name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="exampleInputEmail">Email</label>
        <input type="text" class="form-control" id="exampleInputEmail" placeholder="Enter name" wire:model="email">
        @error('email') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="exampleInputbody">Body</label>
        <textarea class="form-control" id="exampleInputbody" placeholder="Enter Body" wire:model="body"></textarea>
        @error('body') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Save Contact</button>
</form>

Step 6: Create Route

In this step, open your routes file and update the following routes into your routes.web.php file:

routes/web.php

Route::get('/form', function () {
    return view('form');
});

Step 7: Create View File

Note that, you need to uses @livewireStyles, @livewireScripts, and @livewire(‘contact-form’) for adding HTML, CSS, and script code into your liveware files.

In this step, create one blade view files that name form.blade.php file inside resources/views/ folder and update the following code into your file:

resources/views/form.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel Livewire Contact Form Tutorial From Scratch - tutsmake.com</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
<body>
    <div class="container mt-5">
        <div class="row mt-5 justify-content-center">
            <div class="mt-5 col-md-8">
                <div class="card">
                  <div class="card-header bg-success">
                    <h2 class="text-white">Laravel Livewire Form Tutorial From Scratch - tutsmake.com</h2>
                  </div>
                  <div class="card-body">
                    @livewire('contact-form')
                  </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>

Step 8: Run Development Server

Finally, you need to run the following PHP artisan serve command to start your laravel livewire form submit example app:

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now, you are ready to run laravel livewire form submit example app. So open your browser and hit the following URL into your browser:

http://localhost:8000/form

Recommended Tutorial

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?