0

i have a log in form in my front end (vue) when users log in, in vue i can get back data of logged in user perfectly fine through

axios.get('http://127.0.0.1:8000/api/user').then((response)=>{
       this.userData = response.data;  

However in my backend when i try to bring back the logged in user though

 if ($request->user('sanctum')) {
    return "auth";
} else {
    return "guest";
} 

it returns guest i dont know why!!!!

vue code:

 async login(){ 
             
                     axios.post('http://127.0.0.1:8000/api/login', this.form).then((response) =>{
                    localStorage.setItem('token', response.data);
               axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
                     this.$router.push('/');
                        } )
                      
                .catch ((error) =>{
                  console.log(error.response.data.errors);
                })
               
            },

laravel auth controller :

 public function loginn(Request $request){
      $request->validate([
         'email' => 'required',
         'password' => 'required',
        ]);

         $user = User::where('email', $request->email)->first();
         if (! $user || ! Hash::check($request->password, $user->password)) {
             throw ValidationException::withMessages([
                 'email' => ['The provided credentials are incorrect.'],
             ]);
         }
         return $user->createToken("token")->plainTextToken;
         return response()->json([
            'token' => $token,
            'type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
         ]);

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/signup', [authcontroller::class, 'signupp']);
Route::post('/login', [authcontroller::class, 'loginn'])->name('login');;
Route::post('/logout',[authcontroller::class, 'logout'])->middleware('auth:sanctum');
aliana
  • 47
  • 5

1 Answers1

0

I haved this problem. This problem is for .env in backend laravel and get csrf front remembering that the localhost address must be either localhost or 127.0.0.1 amd get csrf before

axios.get('/sanctum/csrf-cookie').then(response => { // Login...

}); 

.env SESSION_DOMAIN=127.0.0.1 SACTUM_STATEFUL_DOMAINS=127.0.01:PORT

Vito M
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 20 '23 at 02:52