Updated March 24, 2023
Introduction to Validation in Laravel
Validating data goes hand in hand with web application development. You have the freedom to use one of the many ways of validating data available in Laravel. ‘ValidatesRequests’ provides you with a lot of validation rules which are very powerful in order to validate data coming through an HTTP request.
Defining Routes
We in the first place will be defining two routes here in our file ‘routes/web.php’. Get and Post is the two said routes. The form will be displayed to the user with the help of Get and data will be stored in the database using Post.
So the route definition will be as follows:
Route::get('ExampleForm'/create, 'MyController@create');
Route::post('ExampleForm', 'MyController@store');
Creating Controller
Now let’s create a controller where we will create a function to get data from users and store that data. If you are not familiar with creating a controller, then go through below bullet points of creating a controller otherwise move directly to Validation logic.
- Use the below artisan command to create the controller.
Php artisan make:Controller MyController
- With the above command, MyController.php file will be created whose default code is as below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class MyController extends Controller
{
/**
* Form shown to user
* @return Response
*/
public function create()
{
return view('ExampleForm.create');
}
/**
* Function to Store data.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
// Validating and storing data
}
}
Validation Logic
In order to validate data, we will insert validation logic in the store() method. The ‘Validate’ method will be used from the object ‘Illuminate\Http\Request’ for data validation.
Now you can insert your validation rules in-store method as follows:
/**
* Store data.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validation = $request->validate([
'name' => 'required|unique:ExampleForm|max:255',
'email' => 'required',
]);
// Data is valid.
}
Here we can specify our own custom validation rules in method ‘validate’. The controller will keep running until and unless the validation rules specified by you fail. After your validation rule encounters a fail, an error response will be thrown and an error message will be visible to the user.
Example:
$request->validate([
'name' => 'bail|required|unique:ExampleForm’|max:255,
'email' => 'required',
]);
Here, if ‘max’ rule validation fails, then ‘unique’ rule will be ignored. This shows that validation is done in order of rules present in the definition.
Displaying Error
If while executing the controller, any validation rule fails then the user will automatically be redirected to the location the user was in before validation fails. So if we talk about the example we took before, the user should automatically be redirected to create a method. This, in turn, will allow displaying output error responses.
<!-- /resources/views/profile/create.blade.php -->
<h2>Create Profile</h2>
@if ($errors->any())
<div class="alert alert-danger">
<ol>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ol>
</div>
@endif
<!-- Create Profile -->
Validation Rules in Laravel
List of some of the most widely used validation rules:
1. accepted: It can only be 1, on, true or yes. It can be used for acceptance of certain terms related to a website.
2. alpha: The text to be validated can only contain alphabets.
3. alpha_num: The text to be validated can only contain alphabets and numbers.
4. alpha_dash: The text to be validated can only contain alphabets, numbers, underscores, and dashes.
5. array: The text to be validated should be an array.
6. boolean: The only accepted values are 0, 1, “0”, “1”, true and false.
7. date: The text to be validated can only be in a date format in accordance with a PHP function.
8. distinct: It applies to arrays. The array to be validated should not contain duplicate values.
9. email: The text to be validated should be an email.
10. ends_with: <value1>,<value2>,..: The text to be validated should end with specified values.
11. image: The input file should be an image with extensions like png, jpeg, gif, bmp, webp, or svg.
12. integer: The text to be validated should be an integer.
13. required: The specified field should contain some value and cannot be left blank or empty.
14. string: The text to be validated should be a string.
Validation using Form Requests
When you have to handle complex scenarios of validation, ‘form request’ comes into action. Form request is nothing but a class in which you will insert validation rules. In order to validate using form requests, firstly we need to create form requests.
Let’s see how a form request is created.
php artisan make:request StoreProfile
You have successfully generated the class StoreProfile and it is placed in the directory ‘app/Http/Requests’. Generally, this directory already exists, but if it doesn’t, don’t worry as it gets created as soon as you run the above command.
Let’s see how validation rules are inserted as follows:
/**
* Getting validation rules.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|unique:ExampleForm|max:255',
'email' => 'required',
];
}
Now let’s see how these validation rules get executed. You just have to type-hint your request and that’s it and the incoming request will be validated.
**
* Storing user’s profile.
*
* @param StoreProfile $request
* @return Response
*/
public function store(StoreProfile $request)
{
// Request is valid
// Retrieve validated data
$validated = $request->validated();
}
If while executing the controller, any validation rule fails then the user will automatically be redirected to the location the user was in before validation fails.
Authorization of Form Requests
‘authorize’ method can be used in order to authenticate the user before he performs s any action/operation any resource.
Customization of Error Messages
You can also customize as to what error response should be sent to the user by overriding the method ‘messages’.
public function messages()
{
return [
'name.required' => 'Your name is required',
'email.required' => ‘An email is required',
];
}
Conclusion – Validation in Laravel
Hopefully, so far we have learned enough about validation concepts in Laravel which will enable you to create your web application with validation rules in it, which will be robust and secure at the same time.
Recommended Articles
This is a guide to Validation in Laravel. Here we discuss the introduction, creating controller, validation logic and Validation Rules in laravel. You may also have a look at the following articles to learn more –