How To Validate Form In Laravel 9

In this article, we will see how to validate a form in laravel 9. For any incoming data, we need to validate it before storing it in the database. Laravel provides several different approaches to validate your application's incoming data. It is most common to use the validate method available on all incoming HTTP requests. Laravel 9 includes a wide variety of convenient validation rules that you may apply to data for validation. In laravel 9 you can also add error messages in blade files, and custom validation in laravel 9.

So, let's see form validation in laravel 9 and custom form validation in laravel 9.

Here, we will use has() function in the session to check the error message in laravel 9. Using this example you can check simple form validation as well as you can create your own custom validation in laravel 9.

Step 1: Add Route

First, we have the following routes defined in our routes/web.php file.

<?php

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

 

 

Step 2: Create Controller

Now, we will create UserController to save data in the database. So, copy the below code in your controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function create()
    {
    	return view('index');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
                'name' => 'required',
                'password' => 'required|min:8',
                'email' => 'required|email|unique:users'
            ], [
                'name.required' => 'Name is required',
                'password.required' => 'Password is required',
                'email.required' => 'Email is required'
            ]);
  
        $validatedData['password'] = bcrypt($validatedData['password']);
        $user = User::create($validatedData);
      
        return back()->with('success', 'User Created Successfully !!');
    }   
}

In laravel 9 Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string.

$validatedData = $request->validate([
    'name' => 'required',
    'password' => ['required', 'min:8'],
    'email' => ['required, email, unique:users'],
]);

 

 

Stopping On First Validation Failure

Sometimes we need to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute in laravel 9.

$request->validate([
    'name' => 'bail|required|unique:users|max:255',
    'password' => ['required', 'min:8'],
    'email' => ['bail, required, email, unique:users'],
]);

In this example, if the unique rule on the name attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned. 

 

Step 3: Add Blade File

In this step, we will create a blade file and save the name as index.blade.php

<html>
<head>
    <title>How To Validate Form In Laravel 9 - Techsolutionstuff</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://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
    <div class="container">  
        <div class="row">
            <div class="col-md-12" style="margin-top: 30px;">
                <h1>How To Validate Form In Laravel 9 - Techsolutionstuff</h1>   
                @if(Session::has('success'))
                <div class="alert alert-success">
                    {{ Session::get('success') }}
                    @php
                        Session::forget('success');
                    @endphp
                </div>
                @endif
           
                <form method="POST" action="{{ url('user/store') }}">
                    @csrf
                    <div class="form-group">
                        <strong>Name:</strong>
                        <input type="text" name="name" class="form-control" placeholder="Name">
                        @if ($errors->has('name'))
                            <span class="text-danger">{{ $errors->first('name') }}</span>
                        @endif
                    </div>
           
                    <div class="form-group">
                        <strong>Password:</strong>
                        <input type="password" name="password" class="form-control" placeholder="Password">
                        @if ($errors->has('password'))
                            <span class="text-danger">{{ $errors->first('password') }}</span>
                        @endif
                    </div>
            
                    <div class="form-group">
                        <strong>Email:</strong>
                        <input type="text" name="email" class="form-control" placeholder="Email">
                        @if ($errors->has('email'))
                            <span class="text-danger">{{ $errors->first('email') }}</span>
                        @endif
                    </div>
           
                    <div class="form-group">
                        <button class="btn btn-info btn-submit">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS