Laravel 9 Livewire Submit Form Example Tutorial

Laravel 9 Livewire Submit Form Example Tutorial

Laravel 9 livewire form example; In this tutorial, we will learn how to create and submit form data using livewire package in laravel 9 apps.

Laravel 9 Livewire Submit Form Example Tutorial

Follow the following steps to create and submit form using livewire in laravel 9 apps:

  • 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 terminal OR command prompt and run the following command for installing a 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 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, Open a command prompt and run the following command to create the table into database:

php artisan migrate

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

<?php
  
namespace App/Models;
  
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 cmd and run the following command:

php artisan make:livewire contact-form

We 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 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 routes file and update the following routes into routes.web.php file:

routes/web.php

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

Step 7: Create View File

Note that, we need to uses @livewireStyles, @livewireScripts, and @livewire(‘contact-form’) for adding HTML, CSS, and script code into 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 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, we need to run the following PHP artisan serve command to start laravel livewire form submit example app:

php artisan serve

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

php artisan serve --port=8080  

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

http://localhost:8000/form

Recommended Laravel Tutorials

AuthorAdmin

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 *