简体   繁体   English

如何在创建方法 laravel6 后重定向用户?

[英]How to redirect a user after a create method laravel6?

I made a register form in the front_page and I want to redirect the user after a successfull registration to /home page, but instead I get an array and the user is not redirected.我在 front_page 中制作了一个注册表单,我想在成功注册后将用户重定向到 /home 页面,但是我得到了一个数组并且用户没有被重定向。

  {"email":"example@example.com","paypal_email":"example@example.com","updated_at":"2020-02- 
  14 
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}

My route:我的路线:

 Route::post('/', 'Auth\RegisterController@create')->name('auth.register');

Register controller:注册控制器:

      public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);


}    

  public $redirectTo = '/home';

Change this:改变这个:

public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);


}    

to this:对此:

 public function create(Request $request) { $create = User::create([ 'email' => $request['email'], 'paypal_email' => $request['paypal_email'], 'password' => Hash::make($request['password']), ]); if($create){ return redirect('/home'); } //Return errors here }

To learn more about laravel redirects, click here要了解有关 Laravel 重定向的更多信息,请单击此处

You should not call the create method directly, for a few reasons.出于一些原因,您不应直接调用create方法。

  1. the request is not being validated.请求未被验证。
  2. if you want to trigger some events during registration that is not going to happen.如果您想在注册期间触发一些不会发生的事件。
  3. it's not going auto-login the user.它不会自动登录用户。

The create method is really for laravel trait RegistersUsers internal usage. create方法实际上是为 laravel trait RegistersUsers内部使用的。 you can keep the controller like that, you only need to change your route to register .你可以保持这样的控制器,你只需要改变你的路线来register

Route::post('/', 'Auth\RegisterController@register')->name('auth.register');

By doing this the user should be created and redirected to home page.通过这样做,应该创建用户并将其重定向到主页。

And there is a reason why public $redirectTo = '/home';还有一个原因public $redirectTo = '/home'; this attribute exists, by using the create method directly you are ignoring the attribute completely.此属性存在,通过直接使用create方法,您将完全忽略该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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