Johnny
Johnny

Reputation: 301

Laravel custom error displaying

I previously used to include a flash.blade.php file within my blade templates that had rendered my errors from the session to the view using bootstrap alerts. Now I stumbled upon laravel-5-toastr which is really nice and exactly what I'm looking for. I just need to create a new toastr in my controller and redirect the user (or show them a view), and it works:

Toastr::warning($message, $title); return view('xy');

Now I wonder how I can instruct Laravel to output errors using Toastr. I'm talking about validation errors and more stuff. For each and every error, there shall be displayed a seperate toastr. It both -doesn't work- and is considered bad practise to put the "toastr creation code" inside a view. Now, how can I achieve what I want? What I thought of is perhaps something like a middleware that checks whether the session has errors attached and if so, loops through the errors and creates toastrs. However, this doesn't -to me- seem like this was what middleware is for, so I thought of 'something' like that.

Looking forward to seeing suggestions.

Upvotes: 1

Views: 555

Answers (1)

Farzin Farzanehnia
Farzin Farzanehnia

Reputation: 1060

You can manually create validators. For example:

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        foreach($validator->errors()->all() as $error) {
            Toastr::warning($error);
        }
        return back();
    }

    // Do whatever you need to when data is valid
}

You can visit Laravel documentation on the subject.

Upvotes: 2

Related Questions