How to Add Custom Error Messages in Laravel 12

When I started working with Laravel 12, I realized the importance of customizing error messages to provide a better user experience. Default messages can be generic and might not convey the exact issue to the user.

In this guide, I'll walk you through the steps to add custom error messages in Laravel 12, making your application more user-friendly and professional.

Step-by-Step Guide: Adding Custom Error Messages in Laravel 12

Step-by-Step Guide: Adding Custom Error Messages in Laravel 12

 

Example: Custom Error Messages in a Finance or Insurance Form

Let's say you're building a Term Insurance Plans application form or a Car Insurance quote request form using Laravel 12.

Step 1: Create a Route

In your routes/web.php

use App\Http\Controllers\InsuranceController;

Route::get('/insurance/apply', [InsuranceController::class, 'showForm'])->name('insurance.form');
Route::post('/insurance/apply', [InsuranceController::class, 'submitForm'])->name('insurance.apply');

 

Step 2: Create Controller

Run:

php artisan make:controller InsuranceController

Inside app/Http/Controllers/InsuranceController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InsuranceController extends Controller
{
    public function showForm()
    {
        return view('insurance.form');
    }

    public function submitForm(Request $request)
    {
        $request->validate(
            [
                'full_name' => 'required|string|max:255',
                'email' => 'required|email|unique:insurance_quotes,email',
                'age' => 'required|numeric|min:18|max:70',
                'insurance_type' => 'required|in:term,health,car',
            ],
            [
                'full_name.required' => 'Please enter your full name for the insurance application.',
                'email.required' => 'A valid email is required to receive your term insurance quote.',
                'email.unique' => 'This email has already been used to request a car insurance quote.',
                'age.required' => 'Age is required to determine your eligibility for insurance plans.',
                'age.min' => 'Applicants must be at least 18 to apply for health insurance.',
                'age.max' => 'Sorry, our term insurance plans are limited to applicants under 70.',
                'insurance_type.required' => 'Please select your insurance category: term, health, or car.',
                'insurance_type.in' => 'Invalid selection. Choose from term insurance, health, or car insurance.',
            ]
        );

        // Store logic (optional)
        return back()->with('success', 'Your insurance quote request has been submitted!');
    }
}

 

Step 3: Create Blade View

Create file: resources/views/insurance/form.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Apply for Insurance Quote - Laravel 12</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h2>Get Your Free Insurance Quote</h2>

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

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

        <div class="mb-3">
            <label>Full Name</label>
            <input type="text" name="full_name" class="form-control" value="{{ old('full_name') }}">
            @error('full_name') <div class="text-danger">{{ $message }}</div> @enderror
        </div>

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

        <div class="mb-3">
            <label>Age</label>
            <input type="number" name="age" class="form-control" value="{{ old('age') }}">
            @error('age') <div class="text-danger">{{ $message }}</div> @enderror
        </div>

        <div class="mb-3">
            <label>Insurance Type</label>
            <select name="insurance_type" class="form-control">
                <option value="">-- Select Insurance Type --</option>
                <option value="term" {{ old('insurance_type') == 'term' ? 'selected' : '' }}>Term Insurance</option>
                <option value="health" {{ old('insurance_type') == 'health' ? 'selected' : '' }}>Health Insurance</option>
                <option value="car" {{ old('insurance_type') == 'car' ? 'selected' : '' }}>Car Insurance</option>
            </select>
            @error('insurance_type') <div class="text-danger">{{ $message }}</div> @enderror
        </div>

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

 

Conclusion

Customizing error messages in Laravel 12 enhances the user experience by providing clear and specific feedback. Whether you're validating forms directly in controllers or using Form Request classes, Laravel offers flexible ways to define and display custom messages. Implementing these practices will make your application more intuitive and user-friendly.

 

Frequently Asked Questions (FAQs)

  1. How can I validate term insurance form inputs in Laravel 12?

    Use Laravel's built-in validation with custom error messages for fields like name, age, and insurance type.

  2. Is it possible to customize error messages for car insurance quotes in Laravel?

    Yes, Laravel allows full customization of each field’s validation error using the messages array or localization files.

  3. How to display Laravel 12 validation errors in Blade for health insurance forms?

    Use the @error directive next to each input to show user-friendly validation error messages.

  4. Can I localize messages for insurance applications in Laravel 12?

    Yes. You can use the resources/lang/en/validation.php file to manage multilingual error messages and translations.

 

For more detailed information, refer to the official Laravel documentation on Customizing the Error Messages.


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