How To Implement Laravel 9 form validation ?

Today now in this article, i will be share with you how we can implement laravel 9 form validation tutorial. Here we’ll learn about laravel 9 form validation also with an error message. Now in this article goes into with details on form validation in laravel 9. Here i will help you with give an examples of simple form validation in laravel 9 application. By Follow the below step for the laravel 9 form validation with the custom error messages.

We know that Laravel 9 is provides a request object to to add form validation by using it. So here i will use the request validate() for adding the validation rules and also with the custom messages. Here i will use the $errors variable for display an error messages. Now i will show you a very simple step by step example of also know how to add the form validation in the laravel 9 application.

so, let’s the see the below example for adding the form validation.

Laravel 9 Form Validation
Step 1: Install Laravel 9

This step will not needed; however, if we have not created the laravel app, then you may go ahead and then execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Controller

Now in this step, i will create the new FormController for the adding form validation. Now In this controller i will add two method call create() and store(). So let’s create the new controller by using the following command.

php artisan make:controller FormController

Next, let’s need to update 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 Routes

Now need to open routes/web.php file and need to add the routes to manage GET and the POST requests for call the view and also adding 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

Now here i will create the createUser.blade.php file and here i will create the bootstrap simple form also with 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 - CodingsPoint.com</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/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
    
        <h1>Laravel 9 Form Validation Example - CodingsPoint.com</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>

Read Also: How to Create Laravel 9 CRUD Application ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →