php - How can I fix Laravel Call To member function Null?

I am trying to make a project with Laravel. But when trying to login, I am getting an error:

Call to a member function createToken() on null, POST http://127.0.0.1:8000/api/auth/login 500 (Internal Server Error)

Laravel - AuthController.php

  public function login(Request $request){
        $request->validate([
            'email'=>'required|string|email',
            'password'=>'required|string'
        ]);
      
        $credentials = request(['email','password']);
        if(!Auth::attempt($credentials)){
            return response()->json([
                'message'=>'Information is wrong'
            ], 401);
        }
        $user = Auth::user();
        $tokenResult = $user->createToken("Personal Access Token");
        $token = $tokenResult->token;
        $token->save();
        return response()->json([
            'success'=>true,
            'user'=>$user,
            'access_token'=>$token,
            'token_type'=>'Bearer',
            'expires_at'=>Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
        ],201);
    }

I added login component because currently I'm getting error like 'Uncaught TypeError: Cannot read properties of undefined (reading 'push')'

const Login = (props) => {
    const [errors,setErrors] = useState([]);
    const [error,setError] = useState(null);

    useEffect(() => {
        if(props.AuthStore.appState != null){
            if(props.AuthStore.appState.isLoggedIn){
                return props.history.push('/');
            }
        }
    },[]);
    const _handleSubmit = async(values, {setSubmitting})=>{
          await axios.post(`${API_URL}/api/auth/login`, {
                    ...values
            }).then(async (result) => {
                const userData = {
                    ...result.data
                };
                const appState = {
                    isLoggedIn:true,
                    user:userData
                }
                await props.AuthStore.save(appState);
                window.location.reload();
            })
            .catch((error)=>{
                setSubmitting(false);
            })
    }
    let arr = [];
    Object.values(errors).forEach(value => {
        arr.push(value);
    })
}

Answer

Solution:

This has nothing to do with React. The error is pretty much straightforward. You are trying to call createToken() on a null value. In your case, it's $user.

$user is null because $request->user gives you the authenticated user. Your action is login which means the user is not authenticated yet.

You should use Auth::user(); instead.

Source