Laravel 9 Form Validation Tutorial Example

This article covers the details on form validation in Laravel 9. We will take up simple examples of simple form validation in Laravel 9.

Laravel 9 offers a request object to add form validation using it. We will be using request validate () for adding validation rules and custom messages.  We will also be using the $errors variable to display error messages.

Let’s consider the below example for adding form validation

Step 1: Install Laravel 9

If you have not created the Laravel app, then run the below command:

composer create-project laravel/laravel example-app

Step 2: Create Controller

Create a new FormController for adding form validation. In this controller, we use two methods call create() and store(). Let’s create a new controller by running the below command

php artisan make:controller FormController

and updating the following code to that file.

app/Http/Controllers/FormController.php

<?php 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class FormController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }
      
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
  
        $validatedData = $request->validate([
                'name' => 'required',
                'password' => 'required|min:5',
                'email' => 'required|email|unique:users'
            ], [
                'name.required' => 'Name field is required.',
                'password.required' => 'Password field is required.',
                'email.required' => 'Email field is required.',
                'email.email' => 'Email field must be email address.'
            ]);
    
        $validatedData['password'] = bcrypt($validatedData['password']);
        $user = User::create($validatedData);
          
        return back()->with('success', 'User created successfully.');
    }
}

Step 3: Create Route

Open the routes/web.php file and add the routes to manage GET and POST requests for call view and add form validation.

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FormController;
  
/* 
|--------------------------------------------------------------------------
| 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('user/create', [ FormController::class, 'create' ]);
Route::post('user/create', [ FormController::class, 'store' ]);

Step 4: Create Blade File

Create a User.blade.php file and bootstrap a simple form with an error validation message. So, let’s create the following file:

resources/views/createUser.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Form Validation Example</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
    
        <h1>Laravel 9 Form Validation Example</h1>
       
        @if(Session::has('success'))
        <div class="alert alert-success">
            {{ Session::get('success') }}
            @php
                Session::forget('success');
            @endphp
        </div>
        @endif
    
        <!-- Way 1: Display All Error Messages -->
        @if ($errors->any())
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
       
        <form method="POST" action="{{ url('user/create') }}">
      
            {{ csrf_field() }}
      
            <div class="mb-3">
                <label class="form-label" for="inputName">Name:</label>
                <input 
                    type="text" 
                    name="name" 
                    id="inputName"
                    class="form-control @error('name') is-invalid @enderror" 
                    placeholder="Name">
  
                <!-- Way 2: Display Error Message -->
                @error('name')
                    <span class="text-danger">{{ $message }}</span>
                @enderror
            </div>
     
            <div class="mb-3">
                <label class="form-label" for="inputPassword">Password:</label>
                <input 
                    type="password" 
                    name="password" 
                    id="inputPassword"
                    class="form-control @error('password') is-invalid @enderror" 
                    placeholder="Password">
  
                <!-- Way 3: Display Error Message -->
                @if ($errors->has('password'))
                    <span class="text-danger">{{ $errors->first('password') }}</span>
                @endif
            </div>
       
            <div class="mb-3">
                <label class="form-label" for="inputEmail">Email:</label>
                <input 
                    type="text" 
                    name="email" 
                    id="inputEmail"
                    class="form-control @error('email') is-invalid @enderror" 
                    placeholder="Email">
  
                @error('email')
                    <span class="text-danger">{{ $message }}</span>
                @endif
            </div>
     
            <div class="mb-3">
                <button class="btn btn-success btn-submit">Submit</button>
            </div>
        </form>
    </div>
</body>
</html>

Run Laravel App

Type the below command and hit enter to run the Laravel app:

php artisan serve

Now, move to your web browser, type the given URL and view the app output:

http://localhost:8000/user/create

Output:

laravel 9 form validation


Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/mydevhelp.com/public_html/wp-includes/functions.php on line 5420

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/mydevhelp.com/public_html/wp-includes/functions.php on line 5420