Skip to content
Advertisement

How to authenticate after register in Laravel

In my project I am trying to validate that registration information and authenticate myself when I register. But what is happening is that when you register, you send me to the Login page, this happens because when I click on the register button, you send me to a route protected by the Middleware “Auth”. That is, you are not authenticating in the same registration action.

protected function create(RequestFormRegister $data)
{
    $userCount = User::where(['email'=> $data['email']])->count();
    if($userCount>0){
        return redirect()->back()->with('error', '¡El correo ya existe!');
    }else{
        $user = User::create([
            'nombres' => $data['nombres'],
            'apellidos' => $data['apellidos'],
            'ni' => $data['ni'],
            'role_id' => 2,
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'password_confirmation' => Hash::make($data['password_confirmation']),
            'remember_token'=> str_random(15),
        ]);

    }

}

With the previous function the system records the data in BD. But then I have to go to the login. (Thing I don’t want)

If I use the function that laravel brings by default

 protected function create(array $data)
{
    User::create([
        'nombres' => $data['nombres'],
        'apellidos' => $data['apellidos'],
        'ni' => $data['ni'],
        'role_id' => 2,
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'password_confirmation' => Hash::make($data['password_confirmation']),
        'remember_token'=> str_random(15),
    ]);

}

I get the following error enter image description here

What would be the solution for this case. I am using Laravel 5.8 and AdminLte as a template

Advertisement

Answer

You can manually login the newly created user and redirect it to homepage.

protected function create(RequestFormRegister $data)
{
    $userCount = User::where(['email'=> $data['email']])->count();
    if($userCount>0){
        return redirect()->back()->with('error', '¡El correo ya existe!');
    }else{
        $user = User::create([
            ...
        ]);

      // Manually logging user 
      Auth::login($user);
      return redirect()->route('homepage');

    }

}

https://laravel.com/docs/master/authentication#other-authentication-methods

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement