In this tutorial, we will learn Laravel 9 form validation rule with an example. You will also learn Laravel 9 form validation with an error message. We will show you how you can add the custom error message for a particular type of validation in Laravel 9.
We will use Laravel’s validate() method to handle validation based on the user input data and we can also define our custom error message too.
If you don’t want to use the validate() method with the request object then you can create a validator instance manually using the Validator facade. Let’s see Laravel 9 form validation rule for example.
Table of Contents |
1. Laravel 9 validate() Method |
2. Laravel 9 Validator() Method |
3. List of Laravel Validation Rule |
4. Example |
01 Laravel 9 validate() Method
The validate()
method accepts two arguments. The first argument should be an array of validation rules [ 'form_field' => 'required']
. The second argument is optional and should be an array of custom error messages [ 'form_field.required' => 'This field is required.']
.
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
If the validation fails, then the error message will be sent back to the view automatically by the validate()
method. You can access $errors
variables in your view.
If the validation passes, then the controller will continue executing normally.
Display the error messages in the view in Laravel
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
Customizing The Error Messages
To customize the error messages you can pass the second argument as an array in the validate()
method. You need to use them [field_name.validation_rule => 'Customized error message']
as below:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
],[
'title.required' => 'Please add title field.',
'title.unique' => 'Title should be unique.',
'title.max' => 'Title should be less than 255 character.',
'body.required' => 'Description is required.',
]);
02 Laravel 9 Validator() Method
If you don’t want to use the validate() method with the request object then you can create a Validator instance manually using the Validator facade. The make
method on the facade generates a new validator instance:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// Return your customized error message
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
The Validator::make()
method accepts 3 arguments. The first argument should be all input array data, for example Validator::make($request->all(), []);
The second argument should be an array of validation rules as we have already seen in the validate()
the method. For example:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
The second argument is optional and should be an array of custom error messages [ 'form_field.required' => 'This field is required.']
. For example:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
],[
'title.required' => 'Please add title field.',
'title.unique' => 'Title should be unique.',
'title.max' => 'Title should be less than 255 character.',
'body.required' => 'Description is required.',
]);
03 List of Laravel Validation Rule
- Accepted
- Accepted If
- Active URL
- After (Date)
- After Or Equal (Date)
- Alpha
- Alpha Dash
- Alpha Numeric
- Array
- Bail
- Before (Date)
- Before Or Equal (Date)
- Between
- Boolean
- Confirmed
- Current Password
- Date
- Date Equals
- Date Format
- Declined
- Declined If
- Different
- Digits
- Digits Between
- Dimensions (Image Files)
- Distinct
- Ends With
- Enum
- Exclude
- Exclude If
- Exclude Unless
- Exclude With
- Exclude Without
- Exists (Database)
- File
- Filled
- Greater Than
- Greater Than Or Equal
- Image (File)
- In
- In Array
- Integer
- IP Address
- JSON
- Less Than
- Less Than Or Equal
- MAC Address
- Max
- MIME Types
- MIME Type By File Extension
- Min
- Multiple Of
- Not In
- Not Regex
- Nullable
- Numeric
- Password
- Present
- Prohibited
- Prohibited If
- Prohibited Unless
- Prohibits
- Regular Expression
- Required
- Required If
- Required Unless
- Required With
- Required With All
- Required Without
- Required Without All
- Required Array Keys
- Same
- Size
- Sometimes
- Starts With
- String
- Timezone
- Unique (Database)
- URL
- UUID
04 Laravel 9 Form Validation Rule Tutorial With Example
Let’s now see the full Laravel 9 form validation rule tutorial with an example.
Step 1: Install Laravel 9
If you already have installed Laravel 9 on your local machine then you can skip this step. You can easily install the fresh version of Laravel 9 by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app
.
composer create-project --prefer-dist laravel/laravel demo-app
or use the following command to install the specific Laravel version
composer create-project laravel/laravel:^9.0 demo_app
Notes: To install Laravel 9 you need PHP 8.0. So make sure you have installed PHP 8.0 in your local WAMP, LAMP, MAMP, etc.
Step 2: Create UserController
Let’s create a UserController
with create()
and store()
methods. To create a controller run the below command:
php artisan make:controller UserController
After running the above command a new file will be created in the Controllers
directory. Let’s open it and add the following code:
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function create()
{
return view('users.create');
}
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.',
'password.min' => 'Password should be minimum of 5 character.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be a valid email address.'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
User::create($validatedData);
return back()->with('success', 'User has successfully created.');
}
}
Step 3: Create Routes
We need to add resource routes in routes/web.php
file to perform the Laravel 9 form validation rule.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('user/create', [ UserController::class, 'create' ]);
Route::post('user/create', [ UserController::class, 'store' ]);
Step 4: Create Blade/HTML File
At last, we need to create a view blade file in the views
folder to perform the Laravel 9 form validation rule with example. Let’s create below blade file.
resources/views/users/create.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Form Validation Rule Tutorial With Example - ScratchCode.IO</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 Rule Tutorial With Example - ScratchCode.IO</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>
Step 5: Output – Laravel 9 Form Validation Rule Tutorial With Example
Hurray! We have completed all steps for the Laravel 9 form validation rule tutorial with an example. Let’s run the below command and see how it’s working.
php artisan serve
After running the above command, open your browser and visit the site below URL:
http://localhost:8000/user/create
Additionally, read our guide:
- Laravel 9 CRUD Operations With Example Tutorial
- Laravel: Switch Case Statement In Controller Example
- Laravel: Change Column Type In Migration
- 2fa Laravel With SMS Tutorial With Example
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Update Pivot Table In Laravel
- How To Install Vue In Laravel 8 Step By Step
- How To Handle Failed Jobs In Laravel
- Best Ways To Define Global Variable In Laravel
- How To Get Latest Records In Laravel
- Laravel Paypal Integration Tutorial With Example
- How To Pass Laravel URL Parameter
- Laravel Run Specific Migration
- Laravel Notification Tutorial With Example
- How To Schedule Tasks In Laravel With Example
- Laravel Collection Push() And Put() With Example
That’s it from our end. We hope this article helped you learn the Laravel 9 form validation rule tutorial with an example.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!