How to create livewire form in laravel with example

How to create livewire form in laravel with example

Hello friends, Today in this article i am going to write to create livewire form in laravel 7 with example. There are lots of methods available to create a form in laravel. For example we can create blade template file with raw html form element or we can use laravel html collective package to create forms.

If we write raw html then we will need a lot of lines of code to create a form and integrating jquery and ajax would be more hactic and time consuming. That’s why here we will create livewire form in laravel 7.

Laravel livewire form provides advance features to create form. We can create integrate jquery and ajax easily in the livewire form. So please follow the steps below to create livewire form in the simplest way.

In this article i am going to create basic contact form with some fields like name, email, subject and comment. 

Step 1: Install Laravel 7

In the first step, we will install a fresh laravel 7 application using the composer command. So open your terminal or command prompt and execute following command.

composer create-project --prefer-dist laravel/laravel contact-example

Above composer command will create a fresh laravel application with latest version. Here i have a name as contact-example to this laravel application.

Step 2 : Create Migration and Model

After installing a new laravel application, we will create migration to create contact table. So open your terminal and run the following artisan command to generate migration file.

php artisan make:migration create_contacts_table

Above command will create a migration file in the database/migrations directory. Now open this file and update with the contact form’s fields as mentioned below. 

<?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->string('subject');
            $table->string('comment');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Now run the migration command to create contacts table in the database using the artisan command below.

php artisan migrate

We have created table to store data. Now we will create a model in the respect of this table using the artisan command given below.

php artisan make:model Contact

After running the above command, a model file would be created in app directory. And open this newly created model file and add column in the fillable array for mass assignment like the code written below. 

app/Contact.php

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

Now, let’s go to the next step that is installation of livewire.

Step 3: Install Livewire

In this step, we will install Livewire package in laravel 7 application using the composer command. So open your terminal and run  the following command.

composer require livewire/livewire

Step 4: Create Component

In this step, we will create component using livewire command as mentioned below.

php artisan make:livewire contact-form

After running the above command, It will create two files ContactForm.php and contact-form.blade.php 

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

Now we will need to update these files according to our requirement. So open and update it for contact form like below.

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 $subject;
    public $comment;
  
    public function submit()
    {
        $validated_data = $this->validate([
            'name' => 'required|min:6',
            'email' => 'required|email',
            'subject' => 'required',
            'comment' => 'required'
        ]);
  
        Contact::create($validated_data);
  
        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="name">Name</label>
        <input type="text" class="form-control" id="name" placeholder="Enter your name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" id="email" placeholder="Enter your email" wire:model="email">
        @error('email') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="subject">Subject</label>
        <input type="text" class="form-control" id="subject" placeholder="Enter a subject" wire:model="subject">
        @error('subject') <span class="text-danger">{{ $message }}</span> @enderror
    </div>

    <div class="form-group">
        <label for="comment">Comment</label>
        <textarea class="form-control" id="comment" placeholder="Put your comment" wire:model="comment"></textarea>
        @error('comment') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Step 5: Create Route

Now, we will need to create route to handle the request from web browser.

So open routes/web.php file and the route as written below.

routes/web.php

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

Step 6: Create View File

Now we will create a form view. As mentaioned in the route, we have used form in view(). So create form.php file and put the codee as mentioned below.

resources/views/form.blade.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    @livewireStyles
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
  
<div class="container">
  
    <div class="card">
      <div class="card-header">
        How to create livewire form in laravel with example
      </div>
      <div class="card-body">
        @livewire('contact-form')
      </div>
    </div>
      
</div>
  
</body>
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
</html>

Note: A point to be note here, we have used @livewireStyles, @livewireScripts and @livewire(‘contact-form’) feature provided by livewire.

After doing all the steps mentioned above, we have successully created livewire form in laravel 7. Now we will need to deploy this project  by which we could see the created form using the command below.

php artisan serve

Now you can open this url in a web browser to see your application.

http://localhost:8000/contact