简体   繁体   中英

How to set custom redirect url in register in laravel?

I overwrite register method in RegistersUsers Trait in RegisterController to this:

public function register(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'username' => 'required|string|max:255|unique:users',
        'password' => 'required|string|min:8|confirmed',
        'phone_number' => [
            'required',
            'min:11',
            'max:11',
            Rule::unique('users')
        ]
    ]);

    $user = User::create([
        'name' => $request['name'],
        'password' => Hash::make($request['password']),
        'username' => $request['username']
    ]);

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

    $code = ActiveCode::generateCode($user);
    $request->session()->flash('phone', $request['phone_number']);
    $request->session()->flash('auth', ['user_id' => $user->id]);

    $user->notify(new ActiveCodeNotification($code, $request['phone_number']));

    return redirect(route('register.token'));

}

As you can see at the end i returned to a custom route, but after registering, it will redirect to /home .

And this is protected $redirectTo = '/';

Why it can't redirect to route('register.token') ?

UPDATE

This is register.token route:

Route::get('/register/phone', 'Auth\RegisterController@showTokenForm')
->name('register.token');

And this is showTokenForm method:

public function showTokenForm(Request $request)
{
    $request->session()->reflash();

    return view('auth.register-token');
}

The guest middleware is being applied to your route. Use php artisan route:list to see what middleware it says is attached to it. The guest middleware is applied to all the actions of the RegisterController by default, it is set in the constructor of the controller. You will have to adjust that:

$this->middleware('guest')->except('showTokenForm');

Replace

return redirect(route('register.token'));

by

return redirect()->route('register.token');

Source:https://laravel.com/docs/8.x/redirects#redirecting-named-routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM