Home > Blockchain >  Register user with Vue.js and Laravel
Register user with Vue.js and Laravel

Time:02-04

Created a page of login with vue.js. Sent the data to a laravel controller to create a new user. I sent the data to a controller in laravel to create a new user. After creating the user, I'm trying to redirect to home, with the user authenticated, but when redirecting to home, it goes to login page.

Vue requisition

register(){
        
        axios.post('/api/register', this.form)
            .then(response => {
                window.location.href = "/home";
            });
    }

Route API

Route::post('register', 'Api\RegisterController@register');

Controller Laravel

 public function register(Request $request){
    

    $data = $request->validated();

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

    Auth::login($user);
    Auth::guard()->login($user);
     // Auth::loginUsingId($user->id);


    return response()->json(['message' => 'Salvo com sucesso.','user' => $user]);
}

Route WEB, that is accessed after registration:

Route::group(['middleware' => ['auth']], function () {
  Route::get('/home', function(){
      return view('home')
  });
});

I tried with the code,redirect to home, authenticated , but it is going to the login screen, because of the middlware.

Is there any way to go to the home screen automatically authenticated after registration, without having to log in?

CodePudding user response:

When you're registering using Ajax, Laravel is not using sessions to prevent authentication from unsafe origins, so you end up having no authentication for the current user session even after login.

You need to use other auth guard for stateless auth. There are a bunch of variants, but most simple for you will be Sanctum, which store XSRF-TOKEN in cookies and take auth data from there instead of session.

As an alternative, you may consider using JWT, or other token based authentication, but you still will probably experience some troubles with session as I see you not having your front-end as SPA:

window.location.href = "/home";
  •  Tags:  
  • Related