use redirect to specific page after validation in case of error - Laravel

Asked

Viewed 151 times

0

Well I have the code below

Validation:

class FormNew extends FormRequest{

    public function authorize()
    {
        return true;
    }


    public function rules()
    {

        return [
            'email' => 'required|email',
        ];
    }

    public function messages()
    {

       return [
            'email.required'        => 'campo Email Obrigatório',
            'email.email'           => 'campo Email com formato inválido',
        ];
    }

}

Controller:

class FormularioController extends Controller{

    public function newsletter(FormNew $request)
    {

        $usuarioEmail = Usuario::Where('email', $request->email)->first();

        if($usuarioEmail == null){
            $usuario = new Usuario;
            $usuario->perfil_id         = '2';
            $usuario->email             = $request->email ;
            $usuario->password          = Hash::make(rand(1,100).'senha');
            $usuario->save();
            return redirect('?#newsletters')->with('SucessoCadastro', 'Email Cadastrado com sucesso!');
        }else{
            return redirect('?#newsletters')->with('Falha', 'Email já cadastrado no sistema');
        }


    }
}

Note who in my redirect I am using an anchor, for when the user submits the form he goes straight to where the form is, I wanted to know how to use this redirect within my validation, for when the error is he go p form to show the errors (Formnew).

1 answer

1


The class FormRequest has special properties for redirecting, if it does not find any value it uses the default redirect Illuminate\Routing\UrlGenerator::previous().

You can redirect using any of the properties below:

protected $redirect; // URL. ex: google.com
protected $redirectRoute; // Nome da rota.
protected $redirectAction; // Action do controller 
class FormNew extends FormRequest{

    /**
     * Redirect route when errors occur.
     *  
     * @var string
     */
    protected $redirect = '/teste#newsletters';

    public function authorize()
    {
        return true;
    }


    public function rules()
    {

        return [
            'email' => 'required|email',
        ];
    }

    public function messages()
    {

       return [
            'email.required'        => 'campo Email Obrigatório',
            'email.email'           => 'campo Email com formato inválido',
        ];
    }

}
  • 1

    worked out, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.