Laravel 11 Custom Validation Error Message Example

Sovary November 30, 2024 108
3 minutes read

In this tutorial, we’ll go through the steps to implement form validation with error messages in Laravel 11. Laravel's validation system makes it simple to validate user input and display error messages.

How to Custom Validation Error Message

Following steps below help you to implement validation error message.

  • Step 1 - Install Laravel App
  • Step 2 - Create Controller
  • Step 3 - Create Blade File (View)
  • Step 4 - Adding Route
  • Step 5 - Run Laravel App

Step 1 - Install Laravel

You have to installed Laravel 11 framework. Read this to know how to install Laravel project.

Step 2 - Create Controller

You’ll need a controller to handle form submission and validation logic. Use the Artisan command to create one:

php artisan make:controller FormController

Open file app -> Http -> Controllers -> FormController.blade.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class FormController extends Controller
{
    /**
     * Show the form view.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('create-user');
    }
          
    /**
     * Handle form submission.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $req): RedirectResponse
    {
        // Validate user input
        $validation = $req->validate([
            'name' => 'required',
            'password' => 'required|min:5',
            'email' => 'required|email|unique:users',
        ], [
            'name.required' => 'Name field is required.',
            'password.required' => 'Password field is required.',
            'password.min' => 'Password must be at least 5 characters long.',
            'email.required' => 'Email field is required.',
            'email.email' => 'Email field must be a valid email address.',
            'email.unique' => 'This email is already registered.'
        ]);

        // Hash the password
        $validation ['password'] = bcrypt($validation ['password']);

        // Create the user
        $user = User::create($validation );

        // Redirect back with a success message
        return back()->with('success', 'User created successfully!!!');
    }
}

Step 3 - Create Blade File (View)

Create a Blade template to display the form and error messages. In the resources/views directory, create a file named create-user.blade.php and add the following code

Create file resources -> views -> create-user.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 11 Form Validation</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>Laravel 11 Form Validation</h2>

        @if (session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif

        <form action="{{ route('user.store') }}" method="POST">
            @csrf

            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name') }}">
                @error('name')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
            </div>

            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email') }}">
                @error('email')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
</html>

Step 4 - Adding Route

Define routes for displaying the form and handling the submission. Open the routes/web.php file and add the following:

Open file routes -> web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FormController;


Route::get('/user/create', [FormController::class, 'create'])->name('user.show');
Route::post('/user/create', [FormController::class, 'store'])->name('user.store');

Step 5 - Run Laravel App

Finally, start the development server and test your form:

php artisan serve

Visit http://127.0.0.1:8000/form in your browser. You should see the form with validation. If the form is submitted with invalid data, the errors will display below the respective input fields.

Laravel  Laravel 11 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him