Laravel Request Validations
In Laravel, request validation is a powerful way to ensure that the incoming data to your application meets specific criteria. Laravel provides multiple methods to validate incoming requests, ensuring that the data is clean, secure, and in the correct format before it is processed or stored.
There are several ways to validate requests in Laravel:
1. Using the validate()
Method
The simplest way to validate incoming data is by using the validate()
method in a controller or route closure.
Example in a Controller:
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
// Continue processing with validated data
}
In this example:
required
: The field must not be empty.max:255
: The maximum length of the string is 255 characters.email
: The field must be a valid email address.unique:users
: The value must be unique in theusers
table.min:6
: The password must be at least 6 characters long.
If validation fails, Laravel automatically redirects the user back to the previous page with the validation errors and old input.
2. Using Form Requests
A more organized way to handle validation is by creating a Form Request class. This separates the validation logic from your controller, improving code readability and maintainability.
Step 1: Create a Form Request
You can create a custom form request using the Artisan command:
php artisan make:request StoreUserRequest
This creates a new class in the app/Http/Requests/
directory.
Step 2: Define the Validation Rules
In the generated StoreUserRequest
class, define your validation logic in the rules
method:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
public function authorize()
{
return true; // Authorize the request
}
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
];
}
}
Step 3: Use the Form Request in the Controller
Now, in your controller method, you can type-hint the StoreUserRequest
:
public function store(StoreUserRequest $request)
{
// The validated data is automatically available
$validatedData = $request->validated();
// Continue processing with validated data
}
In this approach, you don’t need to manually call $request->validate()
as validation is automatically applied when the form request is injected.
3. Custom Validation Messages
You can customize the error messages for validation rules by providing a messages()
method in the form request or directly in the validate()
method.
Example in a Form Request:
public function messages()
{
return [
'name.required' => 'The name field is required.',
'email.required' => 'Please enter a valid email address.',
];
}
Example in a Controller:
$validatedData = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
], [
'name.required' => 'The name field is required.',
'email.required' => 'A valid email is required.',
]);
4. Conditional Validation
Laravel allows for conditional validation, where you can apply validation rules based on specific conditions.
Example Using sometimes()
Method:
You can use the sometimes()
method to add rules conditionally:
$request->validate([
'name' => 'required|max:255',
'email' => 'required|email',
]);
$request->sometimes('company', 'required|max:255', function ($input) {
return $input->is_company == true;
});
In this example, the company
field is only required if the is_company
field is true
.
5. Custom Validation Rules
If you need custom validation logic, you can define custom rules. You can do this by creating a custom rule class.
Step 1: Create a Custom Rule
You can generate a custom rule using the Artisan command:
php artisan make:rule Uppercase
This will create a new rule class in the app/Rules
directory.
Step 2: Define the Custom Logic
In the generated class, implement your custom validation logic:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
public function message()
{
return 'The :attribute must be uppercase.';
}
}
Step 3: Use the Custom Rule in Validation
You can now use your custom rule in validation:
use App\Rules\Uppercase;
$request->validate([
'name' => ['required', new Uppercase],
]);
6. Available Validation Rules
Laravel offers a wide variety of built-in validation rules. Some common examples include:
required
: Ensures the field is not empty.email
: Validates an email format.min:num
: Minimum value for numeric fields or minimum length for strings.max:num
: Maximum value for numeric fields or maximum length for strings.unique:table,column
: Ensures the value is unique in the specified database table and column.confirmed
: Checks if two fields match, often used for password confirmation (e.g.,password
andpassword_confirmation
).regex:/pattern/
: Ensures the value matches a given regular expression.date
: Ensures the value is a valid date.exists:table,column
: Validates that the value exists in the database table.
7. Handling Validation Errors
When validation fails, Laravel automatically redirects the user back to the previous page and flashes the validation errors and old input data to the session. These errors can be accessed in your Blade views using the @error
directive or $errors
variable.
Displaying Errors in Blade:
<form method="POST" action="/submit"> @csrf <label for="name">Name:</label> <input type="text" name="name" value="{{ old('name') }}"> @error('name') <div class="error">{{ $message }}</div> @enderror <button type="submit">Submit</button> </form>
This ensures that if validation fails, the user will see the appropriate error messages next to each invalid field.
8. Redirecting on Validation Failure
When validation fails, Laravel will automatically redirect back to the previous page, preserving the old input values and errors. You can customize this redirection if needed by using the withErrors()
method.
Example:
return redirect()->back()->withErrors($validator)->withInput();
This allows for manually handling validation failures and returning the user to the previous page with the errors and old input.
Summary
Laravel provides robust tools for validating incoming requests. You can validate data using the simple validate()
method in a controller or by using custom Form Request classes for more complex scenarios. Laravel makes it easy to work with built-in validation rules, create custom rules, and handle validation errors, helping ensure that the data submitted to your application is clean, secure, and correctly formatted.