Home » Php » php – How to redirect a user after a create method laravel6?

php – How to redirect a user after a create method laravel6?

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.

  {"email":"[email protected]","paypal_email":"[email protected]","updated_at":"2020-02- 
  14 
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}

My route:

 Route::post('/', 'Auth\[email protected]')->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';
How to&Answers:

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

Answer:

You should not call the create method directly, for a few reasons.

  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.
you can keep the controller like that, you only need to change your route to register.

Route::post('/', 'Auth\[email protected]')->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'; this attribute exists, by using the create method directly you are ignoring the attribute completely.