How to validate form in Laravel Example

Laravel’s form validation is one of its most significant features that helps security by validating user input data before processing it. Here in this tutorial, you will learn how to validate form in Laravel without storing data into the database. Laravel provides various validation rules such as required, numeric, email, max, min, and many more, which can be applied to form fields depending on the data type and requirements. Laravel’s form validation not only ensures data accuracy and security but also helps improve user experience by providing appropriate error messages when the user enters invalid data.

laravel form input validation example tutorials

How to Validate Form Data in Laravel

Follow the following steps to validate the forms in laravel apps.

  • Step 1 Install Laravel App
  • Step 2 – Setup Database Credentials
  • Step 3 – Create Model and Migration
  • Step 4 – Make Routes
  • Step 5 – Create Form Controller
  • Step 6 – Create Form Blade File
  • Step 7 – Run Development Server

1. Install Laravel App

First of all download a fresh Laravel app using the following command.

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

Go inside the app

cd laravel-form-validation

2. Setup Database

Now ope the.env file and update the database credentials on it.

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

3. Generate Model and Migration

In this step, add the following command the terminal and generate model and migration file.

php artisan make:model Employee -m

After that, open the database/migrations/create_employees_table.php file and update with the following code.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email');
            $table->string('password');
            $table->string('confirm_password');
            $table->string('mobile_number');
            $table->text('about');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

4. Make Routes

Next, open your routes/web.php file and put two routes on it.

use App\Http\Controllers\FormController;
 
Route::get('create', [FormController::class, 'create']);
Route::post('store', [FormController::class, 'store']);

5. Create Controller

In this step, generate a new controller for form validaiton in laravel example using the below command.

php artisan make:controller FormController

Next, open the app/Http/Controllers/FormController.php file and put the below code on it.

<?php 

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

class FormController extends Controller {
   
  public function create() { 
    
     return view('form'); 
  }  

  public function store(Request $request) 
   { 

      $request->validate([
          'first_name' => 'required|string',
          'last_name' => 'required|string',
          'email' => 'required|string',
          'password' => 'required|string|min:8|confirmed',
          'confirm_password' => 'required|string|min:8',
          'mobile_number' => 'required|string',
          'about' => 'required|string',
      ]);

      // udpate data here

    }
}

6. Create Blade Files

Now create a blade file form.blade.php inside the resources/views directory. Next open the resources/views/form.blade.php file and update the below code on it.

<!DOCTYPE html>
<html lang="en">

<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 class="">
  <div class="wrapper ">
     <div class="main-panel">
       <div class="content">
          <div class="row">  
            <div class="col-md-6">
              <div class="card card-user">  
                <div class="card-header">  
                  <h5 class="card-title">Edit Blog</h5>
                </div>  
                <div class="card-body">
                  @if ($errors->any())
                    <div class="alert alert-danger">
                      <ul>
                        @foreach ($errors->all() as $error)
                          <li>{{ $error }}</li>
                        @endforeach
                      </ul>
                    </div>
                  @endif
               <form method="post" action="/store">
                 {{csrf_field()}}
                 <div class="row">
                    <div class="col-md-12">
                       <div class="form-group">
                           <label> First Name </label>
                           <input type="text" class="form-control @error('first_name') is-invalid @enderror" placeholder="First Name" name="first_name" value="{{ isset($user) ? $user->first_name : '' }}">
                           @error('first_name')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                         </div>
                     </div>
                  </div>             
                <div class="row">               
                  <div class="col-md-12">
                    <div class="form-group">
                          <label> Last Name </label>
                           <input type="text" class="form-control @error('last_name') is-invalid @enderror" placeholder="Last Name" name="last_name" value="{{ isset($user) ? $user->last_name : '' }}">
                           @error('last_name')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                       </div>
                   </div>
                </div>
                <div class="row">
                   <div class="col-md-12">
                       <div class="form-group">
                           <label> Email </label>
                           <input type="text" class="form-control @error('email') is-invalid @enderror" placeholder="Email" name="email" value="{{ isset($user) ? $user->email : '' }}">
                           @error('email')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                        </div>
                    </div>
                </div>
                    
                <div class="row">   
                    <div class="col-md-12">
                        <div class="form-group">
                           <label> Password </label>
                           <input type="text" class="form-control @error('password') is-invalid @enderror" placeholder="Password" name="password" value="{{ isset($user) ? $user->password : '' }}">
                           @error('password')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                        </div>
                    </div>
                </div>
                     
               <div class="row">
                  <div class="col-md-12">
                      <div class="form-group">
                           <label> Confirm Password </label>
                           <input type="text" class="form-control @error('confirm_password') is-invalid @enderror" placeholder="Confirm Password" name="confirm_password" value="{{ isset($user) ? $user->confirm_password : '' }}">
                           @error('confirm_password')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                        </div>
                    </div>
                </div>
                <div class="row">       
                   <div class="col-md-12">
                      <div class="form-group">
                           <label> Mobile Number </label>
                           <input type="text" class="form-control @error('mobile_number') is-invalid @enderror" placeholder="Mobile Number" name="mobile_number" value="{{ isset($user) ? $user->mobile_number : '' }}">
                           @error('mobile_number')
                               <span class="invalid-feedback" role="alert">
                                   <strong>{{ $message }}</strong>
                               </span>
                           @enderror
                        </div>
                    </div>
                </div>
                     
                <div class="row">
                   <div class="col-md-12">
                      <div class="form-group">
                           <label> About </label>
                            <textarea class="form-control textarea @error('about') is-invalid @enderror" placeholder="About" name="about">{{ isset($user) ? $user->about : '' }}</textarea>
                            @error('about')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>
                </div>
                     
               <div class="row">
                   <div class="update ml-auto mr-auto">
                         <button type="submit" class="btn btn-primary btn-round">Update Post</button>
                       </div>
                   </div>
                </form>
               </div>
             </div>
           </div>
          </div>
        </div>
     </div>
  </div>

  </body>
</html>

We can display errors in Laravel app in many ways. Here are some other ways you can display the error messages:

1)  $errors: In this error message we can display whole messages in a loop.

@if ($errors->any())
  <div class="alert alert-danger">
      <ul>
         @foreach ($errors->all() as $error)
             <li>{{ $error }}</li>
         @endforeach
      </ul>
  </div>
@endif

2) has(): I use has() method of $errors object, that way i can check message is exist or not. It take single argument. If “firstname” field validation true then it will add “has-error” class will add, otherwise empty string. We can display it inside div class. Check how we use it.

{{ $errors->has('firstname') ? 'has-error' : '' }}

<input type=”text” class=”form-control @error(‘first_name’) is-invalid @enderror” placeholder=”First Name” name=”first_name” value=”{{ isset($user) ? $user->first_name : ” }}”>

3) first(): I use first() method of $errors object, that way i can get single message field wise. It take single argument. you can see as bellow:

{{ $errors->first('first_name') }}

I hope you enjoy with show the error messages in your blade file. If you have questions please add comments below.