Laravel

Laravel: Display Validation Fail Error Messages in Blade File

Laravel

Laravel: Display Validation Fail Error Messages in Blade File

Laravel provides a powerful validation system to ensure that user inputs meet certain criteria before they are processed. When validation fails, you can easily display error messages to guide users on how to correct their input. In this tutorial, we'll guide you through the process of displaying validation fail error messages in a Blade template in Laravel with an example.

Step 1: Perform Validation

First, make sure you have set up validation rules for your form data in your controller. When validation fails, Laravel will automatically redirect back to the previous page with the validation errors flashed to the session.

For example, let's assume you have a form submission route like this:

Route::post('/submit-form', 'FormController@submitForm');

In your controller, perform the validation like this:

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function submitForm(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            // Add more validation rules as needed
        ]);

        // Process the form data
        // ...
    }
}

Step 2: Display Error Messages in Blade

In your Blade template file (e.g., form.blade.php), you can display the validation error messages using the @error directive. Place the directive next to the input field you want to associate the error message with.

<form action="/submit-form" method="POST">
    @csrf

    <label for="name">Name:</label>
    <input type="text" name="name" value="{{ old('name') }}">
    @error('name')
        <div class="alert alert-danger">{{ $message }}</div>
    @enderror

    <label for="email">Email:</label>
    <input type="email" name="email" value="{{ old('email') }}">
    @error('email')
        <div class="alert alert-danger">{{ $message }}</div>
    @enderror

    <!-- Other form fields -->

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

In the example above, the @error directive is used to display the validation error messages for the name and email fields. The old('field') function is used to repopulate the form fields with the previous input when there is a validation error.

Step 3: Style Error Messages

You can style the error messages using CSS to make them more visually prominent. For example:

.alert {
    background-color: #f8d7da;
    border-color: #f5c6cb;
    color: #721c24;
    padding: 8px;
    margin-top: 5px;
}

Conclusion

Displaying validation fail error messages in a Blade template in Laravel provides a user-friendly way to guide users on correcting their form submissions. By using the @error directive, you can dynamically show error messages next to the respective form fields. This ensures a smoother user experience and helps users provide accurate input to your application.