DEV Community

Adebayo Olukunle
Adebayo Olukunle

Posted on

Handling Forms, Validation Rules, and Error Handling in Laravel

Laravel provides a robust and elegant way to handle form submissions, validate user input, and manage error handling. This ensures data integrity, enhances user experience, and helps prevent security vulnerabilities such as SQL injection and XSS attacks. This article explores the best practices for handling forms, validation rules, and error handling in Laravel.

1. Creating Forms in Laravel

In Laravel, forms are primarily handled using Blade templates with the built-in @csrf directive to protect against cross-site request forgery (CSRF) attacks.

Example: Basic Form

<form action="{{ route('store.product') }}" method="POST">
    @csrf
    <label for="name">Product Name:</label>
    <input type="text" name="name" id="name" required>

    <label for="price">Price:</label>
    <input type="number" name="price" id="price" required>

    <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The @csrf directive generates a hidden token to prevent CSRF attacks.
  • The form uses the POST method to send data to the store.product route.
  • Required fields ensure basic validation at the HTML level.

2. Handling Form Submissions in Controllers

Form submissions in Laravel are typically handled in controllers. The store method processes and validates the form data.
Example: Controller Handling

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        // Validate input
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:1',
        ]);

        // Store data
        Product::create($validatedData);

        // Redirect with success message
        return redirect()->back()->with('success', 'Product added successfully!');
    }
}
Enter fullscreen mode Exit fullscreen mode

Breakdown:

  • The validate() method ensures the request data adheres to defined rules.
  • If validation passes, the product is saved in the database.
  • If validation fails, Laravel automatically redirects the user back with validation errors.

3. Validation Rules in Laravel

Laravel provides numerous validation rules, including:

Some Laravel validation rules and description

Example: Advanced Validation

$request->validate([
    'email' => 'required|email|unique:users,email',
    'password' => 'required|min:8|confirmed',
    'age' => 'nullable|integer|min:18',
]);
Enter fullscreen mode Exit fullscreen mode
  • unique:users,email ensures the email is unique in the users table.
  • password uses confirmed, meaning a password_confirmation field must match.
  • nullable allows the field to be empty without validation errors.

4. Displaying Validation Errors

When validation fails, Laravel redirects back with error messages. In the Blade template, we can display these errors.

Example: Displaying Errors in Blade

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

This will display errors if validation fails.

5. Customizing Validation Error Messages
You can customize validation error messages using the messages() method.

Example: Custom Error Messages

$request->validate([
    'name' => 'required|string',
    'email' => 'required|email|unique:users,email',
], [
    'name.required' => 'The name field is mandatory.',
    'email.unique' => 'This email is already in use.',
]);

Enter fullscreen mode Exit fullscreen mode

6. Form Request Validation

Instead of handling validation directly in controllers, Laravel provides Form Request Validation for cleaner code.

Step 1: Create a Form Request
Run the following command:

php artisan make:request StoreProductRequest
Enter fullscreen mode Exit fullscreen mode

Step 2: Define Validation Rules
Modify the generated StoreProductRequest.php file:

use Illuminate\Foundation\Http\FormRequest;

class StoreProductRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:1',
        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Please enter the product name.',
            'price.numeric' => 'Price must be a valid number.',
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Use It in the Controller

public function store(StoreProductRequest $request)
{
    Product::create($request->validated());
    return redirect()->back()->with('success', 'Product added successfully!');
}
Enter fullscreen mode Exit fullscreen mode

Using Form Request Validation keeps controllers clean and ensures separation of concerns.

7. Error Handling in Laravel

Laravel provides robust error handling through try-catch blocks and custom error pages.

Example: Handling Exceptions in Controllers

use Exception;
use Illuminate\Database\QueryException;

public function store(StoreProductRequest $request)
{
    try {
        Product::create($request->validated());
        return redirect()->back()->with('success', 'Product added successfully!');
    } catch (QueryException $e) {
        return redirect()->back()->with('error', 'Database error: ' . $e->getMessage());
    } catch (Exception $e) {
        return redirect()->back()->with('error', 'An unexpected error occurred.');
    }
}
Enter fullscreen mode Exit fullscreen mode

8. Custom Error Pages

You can customize error pages by modifying the resources/views/errors directory.

Example: Custom 404 Page
Create a file: resources/views/errors/404.blade.php

@extends('layouts.app')

@section('content')
    <h1>Page Not Found</h1>
    <p>Sorry, the page you are looking for does not exist.</p>
    <a href="{{ url('/') }}">Return Home</a>
@endsection
Enter fullscreen mode Exit fullscreen mode

Conclusion

Handling forms, validation, and error handling in Laravel is straightforward and powerful. By utilizing built-in validation rules, form request validation, and error handling mechanisms, developers can create secure and user-friendly applications.

Key Takeaways:

  • Use Laravel’s validate() method for quick validation.
  • Use Form Request Validation for cleaner controllers.
  • Display validation errors properly in Blade views.
  • Implement try-catch blocks for robust error handling.
  • Customize error pages for a better user experience.

By following these best practices, you can efficiently handle form submissions and ensure your Laravel applications remain secure and user-friendly.

Top comments (0)