Laravel 9 Form Validation Example

Websolutionstuff | Feb-12-2022 | Categories : Laravel

 In this tutorial, we will see laravel 9 form validation example. 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 message in blade files, custom validation in laravel 9.

So, let's see form validation in laravel 9, laravel 9 custom validation rule, laravel 9 validation error messages, custom validation message 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>Laravel 9 Form Validation Example - Websolutionstuff</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>Laravel 9 Form Validation Example - Websolutionstuff</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>

 

 

Output :

laravel_9_form_validation_example_output

 


You might also like :

Recommended Post
Featured Post
Laravel 9 orWhere Condition Example
Laravel 9 orWhere Condition Ex...

In this article, we will see the laravel 9 orWhere condition example. Where condition is joined together using the ...

Read More

Oct-13-2022

Datatables Show And Hide Columns Dynamically In jQuery
Datatables Show And Hide Colum...

In this article, we will see how to hide and show columns in datatable in jquery. This example shows how you can ma...

Read More

Jun-07-2022

Laravel 8 Authentication using Jetstream Example
Laravel 8 Authentication using...

In this article, we will discuss laravel 8 authentication with jetstream. This post will give you a simpl...

Read More

Nov-12-2020

Laravel 10 Send Mail using Markdown Template
Laravel 10 Send Mail using Mar...

Hey everyone! Ever wondered how to make your Laravel emails look sleek and professional? In this guide, I'll walk yo...

Read More

Dec-04-2023