概要
Laravelアプリでユーザ登録完了後のリダイレクトパスの変更方法をまとめた個人メモです。
設定
結論から、app/Providers/RouteServiceProvider.php
の以下箇所を変更することでリダイレクト先を変更することが可能です。
デフォルトでは/home
となっています。
app/Providers/RouteServiceProvider.php
public const HOME = '/home';
ユーザ登録のコントローラである、app/Http/Controllers/RegisterController.php
から呼ばれています。
app/Http/Controllers/RegisterController.php
protected $redirectTo = RouteServiceProvider::HOME;
Laravel本体のソースを見ると、トレイトで実装されているRegisterUsers
とRedirectsUsers
により処理が行われていることを確認できます。
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Auth/RegistersUsers.php
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Auth/RedirectsUsers.php
RegisterUsers.php
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());
}
RedirectUsers.php
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}