Skip to content

Laravel - Validation

Validation is a crucial aspect of application development, ensuring that incoming data meets specific criteria before being processed. Laravel provides several convenient ways to validate incoming HTTP request data with a variety of powerful validation rules. By default, Laravel’s base controller class uses the ValidatesRequests trait, which provides a convenient validate method.

Laravel offers a comprehensive list of validation rules. Here are some common ones (this list is not exhaustive):

Commonly Used Validation Rules
accepted
alpha
array
boolean
date_format:format
digits_between:min,max
file (also image, mimes, mimetypes)
ip (also ipv4, ipv6)
min:value
numeric
required
required_with:foo,bar,...
required_without_all:foo,bar,...
string
url

For a complete list and detailed usage, always refer to the official Laravel validation documentation.

When validation fails, Laravel automatically redirects the user back to their previous location (or to a specified URI for AJAX requests). The validation errors are automatically flashed to the session, making them available in your Blade views via the $errors variable. The $errors variable is an instance of Illuminate\Support\MessageBag.

You can display all errors in a list:

@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

Or display errors for a specific field using the @error directive:

<label for="username">Username</label>
<input type="text" name="username" id="username" class="@error('username') is-invalid @enderror">
@error('username')
<div class="alert alert-danger">{{ $message }}</div>
@enderror

Step 1: Create a controller named AuthValidationController.

php artisan make:controller AuthValidationController

Step 2: After successful execution, open app/Http/Controllers/AuthValidationController.php and add the following methods:

app/Http/Controllers/AuthValidationController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthValidationController extends Controller
{
public function showLoginForm()
{
return view('auth.login_form'); // We'll create this view next
}
public function processLogin(Request $request)
{
$validatedData = $request->validate([
'username' => 'required|string|max:20|alpha_num',
'password' => 'required|string|min:8',
'email' => 'nullable|email' // Optional email field
]);
// If validation passes, $validatedData will contain the validated data.
// At this point, you can proceed with authentication or other logic.
// For this example, we'll just return a success message.
return 'Login form submitted successfully with valid data!';
}
}

Step 3: Create a Blade view file at resources/views/auth/login_form.blade.php and add the following HTML form:

resources/views/auth/login_form.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<style>
.alert-danger { color: red; list-style: none; padding-left: 0; }
.is-invalid { border-color: red; }
label, input, button { display: block; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>Login</h1>
@if ($errors->any())
<div class="alert alert-danger">
**Whoops! Something went wrong.**
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="POST" action="{{ url('/validate-login') }}">
@csrf <!-- CSRF Token -->
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="{{ old('username') }}" class="@error('username') is-invalid @enderror">
@error('username')
<div class="alert-danger">{{ $message }}</div>
@enderror
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="@error('password') is-invalid @enderror">
@error('password')
<div class="alert-danger">{{ $message }}</div>
@enderror
</div>
<div>
<label for="email">Email (Optional):</label>
<input type="email" name="email" id="email" value="{{ old('email') }}" class="@error('email') is-invalid @enderror">
@error('email')
<div class="alert-danger">{{ $message }}</div>
@enderror
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>

Note: The old('username') function is used to repopulate the form field with its previous input if validation fails.

Step 4: Add routes for these actions in your routes/web.php file:

routes/web.php

use App\Http\Controllers\AuthValidationController;
Route::get('/login-form', [AuthValidationController::class, 'showLoginForm']);
Route::post('/validate-login', [AuthValidationController::class, 'processLogin']);

Step 5: Visit http://localhost:8000/login-form in your browser.

Step 6: Try submitting the form without entering any data, or with data that violates the rules (e.g., a password less than 8 characters). You will be redirected back to the form, and validation error messages will be displayed.

For more complex scenarios, you can create Form Request classes. These classes allow you to encapsulate your validation logic and authorization checks. Generate a form request using php artisan make:request StorePostRequest. You can then type-hint this request in your controller method, and Laravel will automatically validate the incoming data before your controller method is even called.

Further Learning: Explore custom validation rules, conditional validation, and localizing error messages in the official Laravel documentation.