Search code examples
phplaravel-5.3

Custom redirect path if Registration fails on Laravel 5.3


I want to change the redirect path when the Registration fails in Laravel 5.3 right it redirects to the previous page but I want to change it and I can't find out where.

Here is the RegisterController

<?php
use RegistersUsers;

protected $redirectTo = '/';

public function __construct()
{
    $this->middleware('guest');
}


protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255|min:6',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}
?>

And here is the RegistersUsers trait

<?php
use RedirectsUsers;


public function showRegistrationForm()
{
    return view('auth.register');
}

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

protected function guard()
{
    return Auth::guard();
}

protected function registered(Request $request, $user)
{

}
?>

Is there any ideas on how to achieve that, because I want to make a register Modal on the home page, and since it's a modal the user can't see the errors until he opens the registration Modal again, I want to make the **Failed Registration attempts ** always redirects to /register.

Thank you for helping


Solution

  • Override the RedirectsUsers register function in RegisterController as following.

    public function register(Request $request) {
        $this->validator($request->all())->validate();
    
        $user = $this->create($request->all());
    
        if(empty($user)) { // Failed to register user
            redirect('/register'); // Wherever you want to redirect
        }
    
        event(new Registered($user));
    
        $this->guard()->login($user);
    
        // Success redirection - which will be attribute `$redirectTo`
        redirect($this->redirectPath());
    }