Laravel 9 Work With Livewire Form Submit Tutorial

Reading Time: 7 minutes
1,651 Views

Inside this article we will see the concept i.e Laravel 9 Work with Livewire form submit tutorial. Article contains classified information about submitting a livewire form in laravel9. We will see this form submission concept from scratch.

If you are looking for an article which gives you the information about Livewire form submission in laravel 9 then this article will help you a lot for this.

We will create a form which contains few inputs like – Name, Email, Body and then submit and save form data to database.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Model & Migration

Open project into terminal.

Let’s create model and migration by using a single command.

Creating model and migration …

$ php artisan make:model Contact -m

Above command will create 2 files –

  • Model file with name Contact.php inside /app/Models folder.
  • Migration File with name 2022_07_13_040518_create_contacts_table.php inside /database/migrations folder.

Open up the migration file and write this code snippet

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('body');
            $table->timestamps();
        });
    }

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

Open model file Contact.php and write this code into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'name', 'email', 'body'
    ];
}

Run Migration

Back to terminal and run this command to run migration file.

$ php artisan migrate

It will run all pending migrations of your application. contacts table will be created.

Next,

Install Livewire – A Composer Package

Back to project terminal and run this command to install livewire inside this laravel application.

$ composer require livewire/livewire

You should see like this –

Now, we are able to use the features and functions of livewire.

Generate Livewire Scaffolding

Again,

Back to terminal and run this command to create livewire folder & files.

$ php artisan make:livewire contact-form

Above command will create these files –

  • ContactForm.php file inside /app/Http/Livewire folder.
  • contact-form.blade.php file inside /resources/views/livewire

Open ContactForm.php and write this following code into it.

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\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('/contact-form');
    }

    public function render()
    {
        return view('livewire.contact-form');
    }
}

Open contact-form.blade.php and write this following code into it.

<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>

    <br/>
  
    <div class="form-group">
        <label for="exampleInputEmail">Email</label>
        <input type="text" class="form-control" id="exampleInputEmail" placeholder="Enter email" wire:model="email">
        @error('email') <span class="text-danger">{{ $message }}</span> @enderror
    </div>

    <br/>
  
    <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>

    <br/>
  
    <button type="submit" class="btn btn-primary">Save Contact</button>
</form>
          

Create Blade Template File

Create a blade template file form.blade.php inside /resources/views folder.

Open form.blade.php and write this following code into it.

<html>

<head>
    <title>Laravel 9 Work With Livewire Form Submit Tutorial</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    @livewireStyles
</head>

<body>
    <div class="container mt-4">
        <div class="card">
            <div class="card-header text-center text-white bg-primary">
                <h4 class="text-center">Laravel 9 Work With Livewire Form Submit Tutorial</h4>
            </div>
            <div class="card-body">
                @livewire('contact-form')
            </div>
        </div>
    </div>

    <script src="{{ asset('js/app.js') }}"></script>
    @livewireScripts
</body>

</html>

Add Route

Open web.php file from /routes folder. Add this route into it.

//...

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

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/contact-form

After form data save, you will get records inside your contacts table.

We hope this article helped you to learn Laravel 9 Work With Livewire Form Submit Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more