Laravel 10 Submit Livewire Form Data Tutorial

Reading Time: 7 minutes
357 Views

Forms are an essential part of web development, and Laravel 10 paired with Livewire makes form submissions a joy. We will walk you through the process of submitting Livewire form data in Laravel 10 in this article.

Livewire is a powerful tool for creating interactive and dynamic components without writing a lot of JavaScript code. We will guide you through the steps of creating Livewire components for forms, handling form submissions, performing server-side validation, and providing real-world examples of how to efficiently use Livewire in your online applications.

Read More: Laravel 10 Livewire Pagination Example Tutorial

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

Read More: Laravel 10 Auth with Livewire Jetstream Tutorial

Above command will create 2 files –

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

Open up the migration file and write this complete code,

<?php

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

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

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

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;

    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.

Livewire Installation (Composer Package)

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

$ composer require livewire/livewire

Terminal shell be like,

livewire-installation-laravel-10

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

Next,

Generate Livewire Scaffold Files

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

$ php artisan make:livewire contact-form

Read More: Laravel 10 API Testing Tool Package Tutorial

Above command will create these files –

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

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

<?php

namespace App\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.

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

</div>

Setup 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 10 Submit Livewire Form Data 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 10 Submit Livewire Form Data 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

Read More: Laravel 10 How To Get Logged In User Data Tutorial

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

We hope this article helped you to learn about Laravel 10 Submit Livewire Form Data 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.