How To Create and Validate Form in Laravel 10

Last Updated on by in Laravel
This is a comprehensive Laravel server-side 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 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 Project

Begin the first step by evoking the provided command in the terminal 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=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

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, basically we are adding migration values such as ‘name’, ’email’, ‘phone’, ‘subject’, and ‘message’ in model file using $fillable array.

<?php

namespace App\Models;

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

class Form extends Model
{
    use HasFactory;
    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\Models\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;
use App\Http\Controllers\FormValidtionController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/form', [FormValidtionController::class, 'createUserForm']);
Route::post('/form', [FormValidtionController::class, 'UserForm'])->name('validate.form');

Implement Form Validation in Laravel

In order to process the Laravel Form, we have to create a view file in Laravel. To style the form we are using latest version of Bootstrap 5 CSS framework. Go to resources/views/ folder and create a form.blade.php file, then, update the following code in resources/views/form.blade.php 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>
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

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

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

        <form  method="post" action="{{ route('validate.form') }}" novalidate>

            @csrf

            <div class="form-group mb-2">
                <label>Name</label>
                <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" id="name">

                @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>

            <div class="form-group mb-2">
                <label>Email</label>
                <input type="email" class="form-control @error('email') is-invalid @enderror" name="email" id="email">

                @error('email')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>

            <div class="form-group mb-2">
                <label>Phone</label>
                <input type="text" class="form-control @error('phone') is-invalid @enderror" name="phone" id="phone">

                @error('phone')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>

            <div class="form-group mb-2">
                <label>Subject</label>
                <input type="text" class="form-control @error('subject') is-invalid @enderror" name="subject" id="subject">

                @error('subject')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror                
            </div>

            <div class="form-group mb-2">
                <label>Message</label>
                <textarea class="form-control @error('message') is-invalid @enderror" name="message" id="message" rows="4"></textarea>

                @error('message')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror                     
            </div>

            <div class="d-grid mt-3">
              <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
            </div>
        </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.

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.

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

Start Laravel Application

Run the app using below command.

php artisan serve

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

Conclusion

Laravel server side form validation tutorial is over.

Creating and validating a form is easy in Laravel with its eloquent infrastructure, so far we have understood how to create a form with Bootstrap and implement server side form validation in Laravel application.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.