Laravel - Forms
Laravel - Modern Form Handling
Section titled “Laravel - Modern Form Handling”Laravel greatly simplifies handling HTML forms by integrating seamlessly with its Blade templating engine. Instead of relying on specific form builder packages, modern Laravel development encourages using standard HTML forms, augmented with Blade directives for CSRF protection, repopulating form fields with old input, and displaying validation errors. This approach offers flexibility and leverages Laravel’s built-in capabilities.
Creating a Basic Form
Section titled “Creating a Basic Form”You’ll start by writing standard HTML for your form. Typically, forms submit data using the POST method to a specific route that will handle the submission.
CSRF Protection
Section titled “CSRF Protection”Cross-Site Request Forgery (CSRF) is a type of malicious exploit. Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. To protect your application, you must include the @csrf Blade directive within your HTML form definitions:
<form method="POST" action="/submit-profile"> @csrf ...</form>Retrieving Old Input
Section titled “Retrieving Old Input”When a form submission fails validation, Laravel automatically redirects the user back to the previous location. It also flashes all of the request’s input to the session. You can easily retrieve this flashed input using the old helper function. This is useful for repopulating form fields so the user doesn’t have to re-enter everything.
<input type="text" name="username" value="{{ old('username') }}">If the old('username') doesn’t exist (e.g., on the first visit to the form), it will return null.
Displaying Validation Errors
Section titled “Displaying Validation Errors”When validation fails, Laravel also flashes the validation errors to the session. These errors are available in your Blade views via the $errors variable, which is an instance of Illuminate\Support\MessageBag. You can use the @error Blade directive to quickly check if validation error messages exist for a given attribute and display them.
<label for="email">Email Address</label><input id="email" type="email" name="email" value="{{ old('email') }}">@error('email') <div class="alert alert-danger">{{ $message }}</div>@enderrorThe $message variable within the @error directive contains the error message for that field.
Complete Example: Contact Form
Section titled “Complete Example: Contact Form”Let’s create a simple contact form that collects a user’s name, email, and message.
Step 1: Create the View
Section titled “Step 1: Create the View”Create a Blade view file at resources/views/contact.blade.php:
resources/views/contact.blade.php
<!DOCTYPE html><html><head> <title>Contact Us</title> <style> .alert-danger { color: red; margin-top: 5px; } .alert-success { color: green; margin-top: 10px; } label { display: block; margin-top: 10px; } input[type='text'], input[type='email'], textarea { width: 100%; padding: 8px; margin-top: 5px; box-sizing: border-box; } button { margin-top: 15px; padding: 10px 15px; } </style></head><body> <h1>Contact Us</h1>
@if(session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif
<form method="POST" action="{{ route('contact.submit') }}"> @csrf
<div> <label for="name">Name:</label> <input type="text" id="name" name="name" value="{{ old('name') }}" required> @error('name') <div class="alert alert-danger">{{ $message }}</div> @enderror </div>
<div> <label for="email">Email:</label> <input type="email" id="email" name="email" value="{{ old('email') }}" required> @error('email') <div class="alert alert-danger">{{ $message }}</div> @enderror </div>
<div> <label for="message">Message:</label> <textarea id="message" name="message" rows="5" required>{{ old('message') }}</textarea> @error('message') <div class="alert alert-danger">{{ $message }}</div> @enderror </div>
<div> <button type="submit">Send Message</button> </div> </form></body></html>Step 2: Create the Controller
Section titled “Step 2: Create the Controller”Generate a controller using Artisan:
php artisan make:controller ContactFormControllerThen, add methods to show the form and handle its submission in app/Http/Controllers/ContactFormController.php:
app/Http/Controllers/ContactFormController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ContactFormController extends Controller{ // Show the contact form public function create() { return view('contact'); }
// Handle the form submission public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|max:255', 'message' => 'required|string|min:10', ]);
// Process the data (e.g., send an email, save to database) // For this example, we'll just redirect back with a success message. // Mail::to('admin@example.com')->send(new ContactMail($validatedData));
return redirect()->route('contact.form') ->with('success', 'Your message has been sent successfully!'); }}Note: The validate method will automatically redirect the user back to the form if validation fails, along with the error messages.
Step 3: Define the Routes
Section titled “Step 3: Define the Routes”Add the following routes to your routes/web.php file:
routes/web.php
use App\Http\Controllers\ContactFormController;
Route::get('/contact', [ContactFormController::class, 'create'])->name('contact.form');Route::post('/contact', [ContactFormController::class, 'store'])->name('contact.submit');Step 4: Test the Form
Section titled “Step 4: Test the Form”Navigate to /contact in your browser. You should see the contact form.
Try submitting the form without filling out all fields to see the validation errors.
If you fill it out correctly, you should be redirected back to the form with a success message.
This modern approach to forms in Laravel is powerful, secure, and aligns well with standard web development practices.