• Fri, Mar 2026

Laravel Forms and Validation: Collect and Secure User Input

Laravel Forms and Validation: Collect and Secure User Input

This in-depth tutorial will guide you through everything you need to know about creating forms and handling validation in Laravel. From building simple form fields to applying advanced validation rules, you’ll learn how to collect and secure user input with confidence.

Introduction

One of the most common tasks in web development is collecting data from users. Whether it’s a registration form, login form, or contact form, you need a way to capture input safely. Laravel provides a powerful system for building forms and validating input effortlessly. In this guide, we’ll explore how to create forms, validate them, and secure user data using Laravel’s built-in features.

Why Forms and Validation Are Important

Forms are the gateway to collecting data in your application. Validation ensures the data collected is accurate, safe, and secure before it’s processed or stored in your database. Without proper validation, your application could face problems like:

  • Storing incorrect or incomplete data.
  • Security vulnerabilities such as SQL Injection or XSS attacks.
  • Poor user experience due to unclear or missing error messages.

Setting Up the Project

Before diving in, let’s set up a fresh Laravel project to work with forms.

composer create-project laravel/laravel laravel-forms

Next, start the local server:

php artisan serve

Creating a Simple Form

Step 1: Create a Route


// routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;

Route::get('/contact', [ContactController::class, 'index']);
Route::post('/contact', [ContactController::class, 'store']);
    

Step 2: Create a Controller

php artisan make:controller ContactController

// app/Http/Controllers/ContactController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index()
    {
        return view('contact');
    }

    public function store(Request $request)
    {
        dd($request->all()); // For debugging input
    }
}
    

Step 3: Create the Blade View



<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
</head>
<body>
    <form action="/contact" method="POST">
        @csrf
        <label for="name">Name:</label>
        <input type="text" name="name"><br>

        <label for="email">Email:</label>
        <input type="email" name="email"><br>

        <label for="message">Message:</label>
        <textarea name="message"></textarea><br>

        <button type="submit">Submit</button>
    </form>
</body>
</html>
    

Understanding CSRF Protection

Notice the @csrf directive in the form. Laravel automatically includes CSRF tokens to protect against cross-site request forgery attacks. This ensures that only authorized forms from your application can submit data.

Applying Basic Validation

Now let’s add validation to ensure users provide correct input.


// app/Http/Controllers/ContactController.php
public function store(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|min:3',
        'email' => 'required|email',
        'message' => 'required|max:500'
    ]);

    return "Form validated successfully!";
}
    

Displaying Validation Errors in Blade

Validation errors can be displayed directly in the form using Blade directives:


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

Using Form Requests for Clean Validation

For larger applications, it’s better to use Form Request classes for validation.

php artisan make:request ContactRequest

// app/Http/Requests/ContactRequest.php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|min:3',
            'email' => 'required|email',
            'message' => 'required|max:500',
        ];
    }
}
    

// app/Http/Controllers/ContactController.php
use App\Http\Requests\ContactRequest;

public function store(ContactRequest $request)
{
    return "Form validated with FormRequest!";
}
    

Customizing Validation Messages


public function messages()
{
    return [
        'name.required' => 'Your name is required!',
        'email.email' => 'Please provide a valid email address.',
    ];
}
    

Advanced Validation Rules

  • unique:users,email – ensures email is unique.
  • confirmed – ensures confirmation field matches.
  • regex:/^[A-Za-z0-9]+$/ – matches a pattern.

Validation Rule Reference Table

Here are some commonly used validation rules in Laravel:

RuleDescription
requiredField must not be empty
emailMust be a valid email address
max:valueMaximum length or value
min:valueMinimum length or value
unique:tableValue must be unique in a table

Handling Old Input

When validation fails, Laravel automatically redirects back with the old input. In your Blade form, you can use:


<input type="text" name="name" value="{{ old('name') }}">
    

File Upload Validation


$request->validate([
    'avatar' => 'required|image|mimes:jpg,png,jpeg|max:2048',
]);
    

Best Practices for Forms and Validation

  • Always use @csrf for protection.
  • Keep validation rules in Form Requests for reusability.
  • Show clear error messages to users.
  • Use old() to repopulate forms on error.
  • Validate file uploads carefully to prevent abuse.

Conclusion

Laravel makes form handling and validation straightforward, secure, and flexible. With CSRF protection, built-in validation rules, error handling, and form requests, you can confidently build forms that not only collect data but also safeguard your application. By mastering these concepts, you’ll be well-prepared to create professional-grade web applications that deliver both functionality and security.

This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy