Laravel

How to add custom error message to the error bag without validation in Laravel 8.x?

Share your learning

Often we need to add a custom error message to the error bag without validation in our laravel application.

So, today we are going to discuss this scenario in depth. Let’s get started.

Add error message to the Laravel message bag

If you have a custom error message that you want to inject into Laravel’s error bag, you can do so by using the Laravel MessageBag class.

Here’s an example of how you can achieve this:

Example of message bag in Laravel

use Illuminate\Support\MessageBag;

public function store(Request $request)
{
    $errors = new MessageBag();
    $errors->add('custom_key', 'Your custom error message goes here');

    return redirect()->back()->withErrors($errors)->withInput();
}

In the above example, we create a new instance of the MessageBag class and add a custom error message to it using the add() method. The first parameter of the add() method is the key name you want to assign to the error message, and the second parameter is the error message itself.

Then, we redirect back to the previous page with the errors injected into the error bag using the withErrors($errors) method. The withInput() method is used to repopulate the form fields with the previously entered values.

Use of custom error in the blade view file

In your view, you can access the custom error message using the assigned key name:

<!-- View file -->
@error(‘custom_key’)
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

By following this approach, you can inject a custom error message with a specific key name into Laravel’s error bag and display it in your views.

That’s it, See you in the next Laravel hack, tips & tricks.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago