Laravel 10 Liveware Form Submit Example Tutorial

If you’re looking to create a form using the Livewire package in your Laravel web application, validate the form data, and store it in a MySQL database, this tutorial is perfect for you. By following this tutorial, you’ll learn how to submit and store form data using the Livewire package in your Laravel web application.

Laravel 10 Liveware Form Submit Example Tutorial

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

  • Step 1: Setup New Laravel Project
  • Step 2: Configure Database with Laravel Project
  • Step 3: Create File For Migration and Model
  • Step 4: Install and Configure Livewire
  • Step 5: Create Livewire Form Component
  • Step 6: Add Routes
  • Step 7: Create Blade View and Import Livewire Component
  • Step 8: Run Development Server

Step 1: Setup New Laravel Project

First of all, Open your terminal OR command prompt.

Then execute the following command into it to download and install a new laravel setup in your server:

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

Step 2: Configure Database with Laravel Project

Once you have installed laravel app in your server. Then you need to configure the database with laravel app.

So, visit the project root directory and find & open .evn file. Then add database detail like following:

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: Create File For Migration and Model

In this step, create a model and migration file by executing the following command on cmd or terminal:

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 and Configure Livewire

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

composer require livewire/livewire

Step 5: Create Livewire Form Component

In this step, You need to create the livewire components. So Open your cmd or terminal and execute the following command for that:

php artisan make:livewire contact-form

Once you have executed the previous step command, you need to go to the following paths where you will find the files:

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

Next, update the following code in 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: Add Routes

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 Blade View and Import Livewire Component

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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *