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
How To Get Current User Location In Laravel 9
How To Get Current User Locati...

In this article, we will see how to get the current user location in laravel 9. Many times we are required to...

Read More

Mar-23-2022

Multiple Row Grouping Datatables jQuery
Multiple Row Grouping Datatabl...

In this article, we will see how to row group in datatable in jquery. Datatables doesn't have row grouping buil...

Read More

Jun-04-2022

Laravel 9 Phone Number Validation Using Regex
Laravel 9 Phone Number Validat...

In this article, we will see laravel 9 phone number validation using regex. In laravel 9 we will see different meth...

Read More

Oct-25-2022

How To Install VueJs In Laravel
How To Install VueJs In Larave...

In this article, we will see how to install vue js in the laravel framework. if you are not aware of you are freshe...

Read More

Jul-12-2020