Laravel 12 Form Validation: Step-by-Step Guide

Hi there! In this tutorial, I will guide you through the process of validating forms in Laravel 12. Form validation is an essential part of any web application to ensure that users submit valid and accurate data. Laravel 12 provides an easy and powerful way to validate form inputs using built-in validation rules.

In this example, I will show you how to validate form inputs using controller validation and form request validation. I will also cover how to display custom error messages.

Laravel 12 Form Validation: Step-by-Step Guide

Laravel 12 Form Validation: Step-by-Step Guide

 

Step 1: Install Laravel 12

If you haven't installed Laravel 12 yet, you can do so using the following command:

composer create-project laravel/laravel form-validation

 

Step 2: Create a Controller

Now, let's create a controller to handle the form submission and validation.

php artisan make:controller FormController

 

Step 3: Create a Route

Open the routes/web.php file and define the routes for displaying the form and handling the form submission:

use App\Http\Controllers\FormController;

Route::get('/form', [FormController::class, 'showForm']);
Route::post('/form', [FormController::class, 'submitForm']);

 

Step 4: Create a Form View

Now, create a Blade view to display the form.

resources/views/form.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 12 Form Validation</title>
</head>
<body>

<h2>Laravel 12 Form Validation Example</h2>

@if ($errors->any())
    <div style="color: red;">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form action="{{ url('/form') }}" method="POST">
    @csrf
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name">
    </div>
    <br>
    <div>
        <label for="email">Email:</label>
        <input type="email" name="email">
    </div>
    <br>
    <div>
        <label for="password">Password:</label>
        <input type="password" name="password">
    </div>
    <br>
    <button type="submit">Submit</button>
</form>

</body>
</html>

 

Step 5: Handle Form Validation in Controller

Now open the FormController.php file and add the following code:

app/Http/Controllers/FormController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function showForm()
    {
        return view('form');
    }

    public function submitForm(Request $request)
    {
        // Validate the form data
        $request->validate([
            'name' => 'required|min:3|max:50',
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);

        // If validation passes, return success response
        return back()->with('success', 'Form submitted successfully!');
    }
}

 

Step 6: Display Validation Errors

If the form contains any errors, they will be displayed inside the <ul> element in the Blade template like this:

@if ($errors->any())
    <div style="color: red;">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

 

Step 7: Add Custom Error Messages (Optional)

If you want to display custom error messages, modify your controller like this:

app/Http/Controllers/FormController.php

public function submitForm(Request $request)
{
    $messages = [
        'name.required' => 'The name field is required.',
        'email.required' => 'The email field is required.',
        'password.required' => 'The password field is required.',
    ];

    $request->validate([
        'name' => 'required|min:3|max:50',
        'email' => 'required|email',
        'password' => 'required|min:6'
    ], $messages);

    return back()->with('success', 'Form submitted successfully!');
}

 

Step 8: Use Form Request Validation (Optional)

Instead of writing validation logic in the controller, you can create a Form Request Class for cleaner code.

Run the following command:

php artisan make:request FormRequest

app/Http/Requests/FormRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function messages()
    {
        return [
            'name.required' => 'The name field is required.',
            'email.required' => 'The email field is required.',
            'password.required' => 'The password field is required.',
        ];
    }
}

Then modify your controller like this:

app/Http/Controllers/FormController.php

use App\Http\Requests\FormRequest;

public function submitForm(FormRequest $request)
{
    return back()->with('success', 'Form submitted successfully!');
}

 

Step 9: Test the Form

Now run your project using the following command:

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS