Laravel 12 Form Validation Tutorial Example | TutorialDev

Today I’m gonna show you in Laravel 12 application how to add form validation.

Laravel 12 introduces a request object to add form validation using it. We will use request->validate() for adding validation rules and custom messages. We will use the $errors variable to display error messages. In the Lravel 12 application, how one can add form validation I will show you in a very simple step-by-step example.

So, let’s see the example below:

Step for Laravel 12 Form Validation with Error Message

  • Step 1: Install Laravel 12
  • Step 2: Create Controller
  • Step 3: Create Routes
  • Step 4: Create Blade File
  • Run Laravel App

 

Laravel 12 Form Validation

 

Step 1: Install Laravel 12

Execute the below command to create the Laravel app:


laravel new example-app

Step 2: Create Controller

Creating a new `FormController` for adding form validation. In this controller, we will add two methods called `create()` and `store()`. So let’s create a new controller using the following command.

 

php artisan make:controller FormController

Next, let’s update the following code in that file.

app/Http/Controllers/FormController.php

<?php

     

namespace App\Http\Controllers;

     

use Illuminate\Http\Request;

use App\Models\User;

use Illuminate\View\View;

use Illuminate\Http\RedirectResponse;

    

class FormController extends Controller

{

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Http\Response

     */

    public function create(): View

    {

        return view('createUser');

    }

         

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Http\Response

     */

    public function store(Request $request): RedirectResponse

    {

        $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 Routes

Furthermore, open `routes/web.php` file and add the routes to manage GET and POST requests for calling views and adding form validation.

routes/web.php

 

<?php




use Illuminate\Support\Facades\Route;




use App\Http\Controllers\FormController;




Route::get('users/create', [ FormController::class, 'create' ]);

Route::post('users/create', [ FormController::class, 'store' ])->name('users.store');

 

 

Read More Blog Posts

Laravel 12 File Upload Tutorial Example Full Guide

Laravel CRUD Application Example Tutorial

Laravel Email Verification for Beginners (A Kid-Friendly Guide!)

 

Step 4: Create Blade File

We will create now createUser.blade.php file and will create a bootstrap simple form with error validation messages:

resources/views/createUser.blade.php

 

<!DOCTYPE html>

<html>

<head>

    <title>Laravel 12 Form Validation Example - ItSolutionStuff.com</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />

</head>

<body>

<div class="container">




    <div class="card mt-5">

        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 12 Form Validation Example - ItSolutionStuff.com</h3>

        <div class="card-body">

            @session('success')

                <div class="alert alert-success" role="alert">

                    {{ $value }}

                </div>

            @endsession

         

            <!-- 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="{{ route('users.store') }}">

           

                {{ 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"><i class="fa fa-save"></i> Submit</button>

                </div>

            </form>

        </div>

    </div> 

</div>

</body>

</html>

Run Laravel App:

All  required steps have been done, now you have to type the below command and hit enter to run the Laravel app:

php artisan serve

 

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

http://localhost:8000/users/create