Form handling and validation are essential parts of any web application. Laravel 11 simplifies this process with built-in validation features, CSRF protection, and error handling in Blade templates.
In this guide, we’ll walk through creating a simple form, validating fields, and displaying error messages in Laravel 11.
1. Creating a Simple Form in Blade
Let’s start by creating a basic form with a username and password field in a Blade template. Ensure you include the CSRF token to prevent the ‘419 Page Expired’ error.
<!-- resources/views/login.blade.php -->
<form action="{{ route('login.submit') }}" method="POST">
@csrf <!-- CSRF token for security -->
<label for="username">Username:</label>
<input type="text" name="username" value="{{ old('username') }}">
@error('username')
<div style="color: red;">{{ $message }}</div>
@enderror
<label for="password">Password:</label>
<input type="password" name="password">
@error('password')
<div style="color: red;">{{ $message }}</div>
@enderror
<button type="submit">Submit</button>
</form>
2. Setting Up Routes
Next, define a route to handle form submission in routes/web.php
:
Route::get('/login', function () {
return view('login');
});
Route::post('/login', [AuthController::class, 'submit'])->name('login.submit');
3. Creating the Controller
Generate a controller using Artisan: php artisan make:controller AuthController
Then, update app/Http/Controllers/AuthController.php
with validation logic:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function submit(Request $request)
{
$request->validate([
'username' => 'required|min:3',
'password' => 'required|max:8'
]);
// Display the submitted data for testing (you can later modify this)
return back()->with('success', 'Form submitted successfully!');
}
}
4. Displaying Validation Errors
Laravel automatically redirects back with errors if validation fails. We use the @error
directive in Blade to display these errors.
Additionally, to show a success message:
@if(session('success'))
<div style="color: green;">{{ session('success') }}</div>
@endif
Conclusion
In this guide, we covered how to:
- Create a form in a Blade template
- Protect the form with CSRF tokens
- Validate input fields using Laravel’s
validate
method - Display error messages using
@error
This is a fundamental concept in Laravel development. You can expand this by handling authentication, integrating databases, or redirecting users upon successful login!