skip to Main Content

I’m having a little bit of a problem, I was wondering if someone could help me out.

I’m trying to learn the Laravel PHP framework, however unfortunately, I can’t seem to accomplish a result.

I am trying to use the Auth::Check function to see if the user is authenticated, I am doing so in my routes as a sort of gate before giving them access to the webpage.

However I’m having an error message, and other people got it, but their answers aren’t solving it for me, and it mentions dependencies like Laravel/ui, but that’s not right, right? they tell you not to use it on a project you’re already working on.

The error appears to be related to IlluminateSupportFacadesAuth;

And it happens on this type of code:

public static function logout() {
   Auth::logout();
   setcookie('token', '', time() - 3600, "/");
   return true;
}

Could someone help me out? I’m a little stumped. The internet talks a lot about this error, but none of them are quite obvious.

I tried deleting the cache, I also tried to look through the classes to see if any errors were visible.

Edit: Someone in the comments requested that I show my config, here they are:

APP_NAME='GPT Translate'
APP_ENV=local
APP_KEY=XXX
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gpt_translate
DB_USERNAME='root'
DB_PASSWORD='root'

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

OPENAI_API_KEY='XXX'

Also, here is the code I’m experiencing the error in, It’s the logout function

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesSession;

class CustomAuth extends Controller
{
    public static function register($email, $name, $password) {
        // Check if email already exists
        $user = User::where('email', $email)->first();
        if ($user) {
            return response()->json([
                'message' => 'Email already exists'
            ], 400);
        }

        // Create new user
        $user = new User();
        $user->email = $email;
        $user->name = $name;
        $user->password = Hash::make($password);
        $user->save();

        return true;
    }

    public static function login($email, $password) {
        // Check if email exists
        $user = User::where('email', $email)->first();
        if (!$user) {
            return false;
        }

        // Check if password is correct
        if (!$user || !Hash::check($password, $user->password)) {
            return false;
        }

        // Create token
        $token = $user->createToken('auth_token')->plainTextToken;

        // Set cookie
        setcookie('token', $token, time() + (86400 * 30), "/");

        // Set session variables
        Session::put('username', $user->email);
        Session::put('name', ucfirst($user->name));
        Session::put('email', $user->email);

        // Return token
        return $token;
    }

    // Verify token
    public static function verifyToken($token = false) {
        // Connected Token
        $connected_token = request()->cookie('token') ?? false;
        $token = $connected_token ?? $token ?? false;

        // Check if token exists
        if (!$token) return false;

        // Check if token is valid
        $user = User::where('remember_token', $token)->first();
        if (!$user) return false;

        // Return
        return true;
    }

    public static function logout() {
        // Logout user use laravl auth (and sanctum)
        Auth::logout();
    }
}

Hope this helps!

2

Answers


  1. I am trying to use the Auth::Check function to see if the user is authenticated, I am doing so in my routes as a sort of gate before giving them access to the webpage.

    Well there is an easier way to do so, you can use a middleware on the route you want to protect. That middleware is ‘auth’. More info: Middlewares in Laravel

    Route::get('/some-route', [MyController::class, 'myFunction'])->middleware('auth');
    

    I am not 100% sure, what are you trying to build. But, if you want to implement an API in Laravel that would be relevant: Sanctum

    Here is a simplified version of your code:

    use AppModelsUser;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesHash;
    use IlluminateSupportFacadesAuth;
    
    
    class CustomAuth extends Controller
    {
        // There is no reason to declare these functions as static, you can also accept a request object in your controller (read more about dependency injection in Laravel)
        public function register(Request $request) {
            // Check if email already exists
            // You need to learn more about validation in Laravel, this is not a safe way to extract data.
            $user = User::where('email', $request->get('email'))->first();
    
            if ($user) {
                return response()->json([
                    'message' => 'Email already exists'
                ], 422); // I would use here 422 instead of 400, again you won't handle this manually, usually you have a validation rule that handles it.
            }
    
            // Create new user, not problematic but I would do it this way
            /*$user = new User();
            $user->email = $email;
            $user->name = $name;
            $user->password = Hash::make($password);
            $user->save();*/
    
            $user = User::Create([
                'email' => $email,
                'name' => $name,
                'password' => Hash::make($password), // there is a more elegant way to do it in the model, but its good for now as a beginner :)
            ]);
    
            // Usually you would like to login the user after registering to do so, just use the login method the Auth provide -> in web only. The second parameter is actually 'Remember me' option.
            Auth::login($user, true);
    
            return view('some-view');
        }
    
        // As previous, There is no reason to declare these functions as static.
        public function login(Request $request) {
            // Check if email exists
            $user = User::where('email', $request->get('email'))->first();
            
            // You already checking for user down below, right?
            /*if (!$user) {
                return false;
            }*/
    
            // Check if password is correct. Yeah works, it is better to learn more about error handling in Laravel :)
            if (!$user || !Hash::check($password, $user->password)) {
                // return false;
                // Again, validation will handle this.
                return redirect()->back()->withErrors(['email' => 'This email is already taken']);
            }
    
            // Create token, why??
            // $token = $user->createToken('auth_token')->plainTextToken;
    
            // Set cookie, no laravel handles that :)
            // setcookie('token', $token, time() + (86400 * 30), "/");
    
            // Set session variables
            //Session::put('username', $user->email);
            //Session::put('name', ucfirst($user->name));
            //Session::put('email', $user->email);
    
            // Return token, you are not implementing an API, are you?
            //return $token;
    
            // Access the properties in the template using $user variable. e.g. $user->email, $user->name …etc.
            return view('some-view', ['user' => $user]);
        }
    
        // Verify token. You don't need this anymore :)
        /*
        public static function verifyToken($token = false) {
            // Connected Token
            $connected_token = request()->cookie('token') ?? false;
            $token = $connected_token ?? $token ?? false;
    
            // Check if token exists
            if (!$token) return false;
    
            // Check if token is valid
            $user = User::where('remember_token', $token)->first();
            if (!$user) return false;
    
            // Return
            return true;
        }*/
    
        public function logout() {
            // Logout user use laravl auth (and sanctum). What??
            Auth::logout();
        }
    }
    
    Login or Signup to reply.
  2. You haven’t logged in with Authentication Faced. Your login function should be like.

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
    
        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('api-token')->plainTextToken;
    
            return response()->json(['token' => $token], 200);
         }
    
        return response()->json(['message' => 'Unauthorized'], 401);
    }
    

    You need to delete token when logout.

    public function logout(Request $request)
    {
        $user = $request->user();
        $user->tokens()->delete();
    
        return response()->json(['message' => 'Logged out'], 200);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search