Share this:

This is a detailed Laravel server-side Form validation tutorial. In this tutorial, we will learn how to build a form from scratch and validate its value using Laravel’s built-in validation method.

Form validation is a technical process in which a user enters information into HTML input fields and a web form checks whether the information entered by the user is correct or not using programming languages.

To validate the form, use the validate method from the Illuminate\Http\Request object in the Laravel template. If the validation fails, this method checks the form values and throws an exception with the appropriate error response message to the user.

We’ve also written a comprehensive guide on How to Create a Laravel CRUD Application. If you’re just getting started with Laravel, you should look into it.

Tutorial Purpose

  • Using Bootstrap, create a responsive form in Laravel.
  • Validate text, email, phone, and text-area form input fields with name, email, phone, subject, and message values.
  • Display the appropriate error response to the user.
  • Form data should be saved in the database.

Table of Contents

  1. Install Laravel Project
  2. Make Database Connection
  3. Model and Database Migrations
  4. Create Form Validation Controller
  5. Register New Routes
  6. Implement Form Validation
  7. Add Custom CSS
  8. Start Laravel Application

Install Laravel Project

Begin by invoking the provided command in the terminal to install a 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 to a MySQL database by including your database information in the.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 a Laravel form, validate it, and store the form data in a database.

So, in order to define the table schema for the Laravel web form, we must first create the Model. To do so, run the following command.

php artisan make:model Form -m

Open the database/migrations/timestamp create forms table.php file and enter the form values you want to save 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');
    }
}

Put the following code in app/Form.php, we’re basically adding migration values like ‘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'
    ];
}

To run the migration, use the command; you can also check the form values in the database table.

php artisan migrate

Create Form Validation Controller

To create the FormValidationController file, use the following command.

php artisan make:controller FormValidtionController

Insert the code below into the app/Http/Controller/FormValidationController.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.');
  }
  
}

To map the Form data, import the Form model.

In the controller file, we must define two functions.

The form is created and rendered in Laravel view by the createUserForm() function.

The second UserForm() function validates the Laravel form and saves the form data to the MySQL database.

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

Define Form Routes in Laravel

The first route uses the GET method to display the Laravel form in the view. The second route uses the POST method to handle form validation, error and success messages, and data storage in the database.

Create the two routes in the routes/web.php file.

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

To process the Laravel Form, we must first create a view file in Laravel. We used the latest version of the Bootstrap 5 CSS framework to style the form. Create a form.blade.php file in the resources/views/ folder, then update the following code in the 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’ve created a contact that a user can use to fill out the values and save them in the database when they click the submit button.

To implement form validation in Laravel, paste the following code into the form.blade.php file. We have implemented the necessary email and phone number validation using regex. If any field generates an error, it will be displayed below the input field.

Add Custom CSS

We will add custom CSS to the Laravel project in this step. Create a /css/style.css file in the public folder and add the CSS code below to it.

.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

The Laravel server side form validation tutorial is now complete.

With Laravel’s eloquent infrastructure, creating and validating a form is simple. So far, we’ve learned how to create a form with Bootstrap and implement server side form validation in a Laravel application.

Share this:

Categorized in: