How To Create and Validate Form in Laravel 7

Last updated on by Digamber
This is a comprehensive PHP 7 Form Validation example tutorial. In this tutorial, we will learn how to create a form from scratch and how to validate the form’s value using Laravel’s built-in validate method.

Laravel 7 Form Validation Example with Bootstrap

Form validation is a technical process where a user provides the information through the HTML input fields and with the help of programming languages web form checks whether the information entered by the user is correct or not.

The validate method can be used in the Laravel template from Illuminate\Http\Request object to validate the form. This method checks the form values and throws the exception with the proper error response message to the user if the validation gets failed.

We have also written a detailed article on How to Create a Laravel CRUD application. You should check out if you are just getting started in Laravel.

Tutorial Objective

  • Create a responsive form in Laravel with Bootstrap.
  • Validate various form input fields such as text, email, phone and text-areas with name, email, phone, subject and message values.
  • Show proper error response to the user.
  • Store form data in the database.

Install Laravel

Run command to install a brand new Laravel project.

composer create-project laravel/laravel --prefer-dist laravel-form-validation

Head over to the project folder.

cd laravel-form-validation

Make Database Connection

Connect Laravel with MySQLdatabase by adding your database details in .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

Model and Database Migrations

Our goal is to create and validate Laravel form and store the form data into the database.

So we need to create the Model to define the table schema for Laravel web form, run the following command to create Model.

php artisan make:model Form -m

Open database/migrations/timestamp_create_forms_table.php file and add the form values that we need to store in the database.

<?php

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

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

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

Place the following code in app/Form.php.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Form extends Model {

    public $fillable = ['name', 'email', 'phone', 'subject', 'message'];
    
}

Use command to run the migration, you can also check the form values in the database table.

php artisan migrate

Create Form Validation Controller

Run the given below command to create FormValidtionController file.

php artisan make:controller FormValidtionController

Place the following code inside the app/Http/Controller/FormValidtionController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Form;

class FormValidtionController extends Controller {

  // Create Form
  public function createUserForm(Request $request) {
    return view('form');
  }

  // Store Form data in database
  public function UserForm(Request $request) {

      // Form validation
      $this->validate($request, [
          'name' => 'required',
          'email' => 'required|email',
          'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
          'subject'=>'required',
          'message' => 'required'
       ]);

      //  Store data in database
      Form::create($request->all());

      //
      return back()->with('success', 'Your form has been submitted.');
  }

}

Import the Form model to map the Form data.

We have to create two functions in the controller file.

The createUserForm() function creates the form and renders the form in Laravel view.

The second UserForm() function is used for validating the Laravel form and saving the form data in the MySQL database.

The validate object is solely responsible for verifying the incoming data from the $request and makes sure whether the form values are correct or not.

Define Form Routes in Laravel

The first route works with the GET method, and it brings the Laravel form in the view. The second route works with the POST method, and it handles the form validation, error and success messages and storing the data in the database.

Open routes/web.php file and create the two routes.

<?php

use Illuminate\Support\Facades\Route;


Route::get('/form', 'FormValidtionController@createUserForm');
Route::post('/form', 'FormValidtionController@UserForm');

Add Custom CSS

In this step, we will add custom CSS in the Laravel project. Create /css/style.css file in public folder and add the following CSS code in the file.

.container {
    max-width: 500px;
    margin: 50px auto;
    text-align: left;
    font-family: sans-serif;
}

form {
    border: 1px solid #1A33FF;
    background: #ecf5fc;
    padding: 40px 50px 45px;
}

.form-control:focus {
    border-color: #000;
    box-shadow: none;
}

label {
    font-weight: 600;
}

.error {
    color: red;
    font-weight: 400;
    display: block;
    padding: 6px 0;
    font-size: 14px;
}

.form-control.error {
    border-color: red;
    padding: .375rem .75rem;
}

Place the following code in the view/form.blade.php file.

<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">

Create Form in Laravel 7 with Bootstrap

In order to process the Laravel Form, we have to create a view in Laravel. So, go to resources/views/ and create a form.blade.php file. Place the below code inside this file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form Validation in Laravel</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <!-- Custom CSS -->
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

<body>
    <div class="container mt-5">

        <!-- Success message -->
        @if(Session::has('success'))
        <div class="alert alert-success">
            {{Session::get('success')}}
        </div>
        @endif

        <form action="" method="post" action="{{ action('FormValidtionController@createUserForm') }}">

            @csrf

            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control" name="name" id="name">
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email"
                    id="email">
            </div>

            <div class="form-group">
                <label>Phone</label>
                <input type="text" class="form-control" name="phone"
                    id="phone">
            </div>

            <div class="form-group">
                <label>Subject</label>
                <input type="text" class="form-control" name="subject"
                    id="subject">
            </div>

            <div class="form-group">
                <label>Message</label>
                <textarea class="form-control" name="message" id="message"
                    rows="4"></textarea>
            </div>

            <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
        </form>
    </div>
</body>

</html>

We have created a contact, a user can use it to fill the values and store the values in the database when clicked on submit button.

Laravel 7 Form Validation Examples

To implement the form validation in Laravel, we have to place the following form code in the form.blade.php file. We have implemented the required, email validation, phone number validation with regex. When any field throws an error then it will be displayed below the input field.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form Validation in Laravel</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <!-- Custom CSS -->
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

<body>
    <div class="container mt-5">

        <!-- Success message -->
        @if(Session::has('success'))
        <div class="alert alert-success">
            {{Session::get('success')}}
        </div>
        @endif

        <form action="" method="post" action="{{ action('FormValidtionController@createUserForm') }}">

            @csrf

            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control {{ $errors->has('name') ? 'error' : '' }}" name="name" id="name">

                <!-- Error -->
                @if ($errors->has('name'))
                <div class="error">
                    {{ $errors->first('name') }}
                </div>
                @endif
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control {{ $errors->has('email') ? 'error' : '' }}" name="email"
                    id="email">

                @if ($errors->has('email'))
                <div class="error">
                    {{ $errors->first('email') }}
                </div>
                @endif
            </div>

            <div class="form-group">
                <label>Phone</label>
                <input type="text" class="form-control {{ $errors->has('phone') ? 'error' : '' }}" name="phone"
                    id="phone">

                @if ($errors->has('phone'))
                <div class="error">
                    {{ $errors->first('phone') }}
                </div>
                @endif
            </div>

            <div class="form-group">
                <label>Subject</label>
                <input type="text" class="form-control {{ $errors->has('subject') ? 'error' : '' }}" name="subject"
                    id="subject">

                @if ($errors->has('subject'))
                <div class="error">
                    {{ $errors->first('subject') }}
                </div>
                @endif
            </div>

            <div class="form-group">
                <label>Message</label>
                <textarea class="form-control {{ $errors->has('message') ? 'error' : '' }}" name="message" id="message"
                    rows="4"></textarea>

                @if ($errors->has('message'))
                <div class="error">
                    {{ $errors->first('message') }}
                </div>
                @endif
            </div>

            <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
        </form>
    </div>
</body>

</html>

Run the app using below command.

php artisan serve

Test the Laravel Form application on: http://127.0.0.1:8000/form

Conclusion

Creating and validating a form is handy in Laravel, so far we have understood how to create a form with Bootstrap and implement form validation in Laravel. I hope you will surely share this tutorial with others and you can find the full code of this tutorial on GitHub.