kgp43
2 years ago
352
6
Laravel

How to flash Toastr error message if validation fails when using FormRequest?

Posted 2 years ago by kgp43

Hi,

How can I flash a Toastr error message if validation fails? I'm using FormRequest.

Normally I just do this, to flash a status message:

Toastr::success('Saved!', 'Changes has been saved');
return back();

I got no place to post error messages though, when using a FormRequest to edit user account. It skip the entire controller, if the validation fails (as it should).

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EditAccountSettings extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // ONLY FOR TESTING !
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'      => 'required|min:5',
            'email'     => 'required|email|max:255'
        ];
    }
}

My controller:

    public function update(EditAccountSettings $request)
    {

        $user = Auth::user();
    
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        
        $user->save();
        
        Toastr::success('Changes has been saved', 'Success!');
        
        return back();
        
    }

Please sign in or create an account to participate in this conversation.