1

I have spent the last hour googling and reading stack posts on this problem, but have been unable to resolve this issue. I attached a try catch and an if statement and I still am getting the call to member function on null error. Here is my code

 try{
            $user = Auth::user();
            if(null !== ($user->wasStripePlan())){
                $data['allSubscriptions'] = (Auth::user()->wasStripePlan()) ? Auth::user()->subscriptions : [];
            }
        }catch (\PDOException $e){
            $data['allSubscriptions'] = false;
        }

Any ideas on solutions?

1
  • 1
    I thought PDOExceptions were thrown when something goes wrong with the database call. Have you tried to just catch \Exception (the parent class)? I think you're not getting a PDOException so it keeps moving through the try block. Commented Jan 18, 2019 at 19:50

2 Answers 2

3

I think you are trying to access the Auth::user() without being logged in. It is going to return null if you are not logged in and there is no need to use try and catch block.

The error is self-explanatory.

Call to member function on null

if you look inside the try block member function call is in the if condition after the Auth::user() which can return null because of a few reasons such as you are not logged in.

if(null !== ($user->wasStripePlan()))

According to the error $user variable is null. Try to figure out why Auth::user() is returning null.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you over thought this one. No need to do a try/catch when simple if/else statements can handle it.

if(isset(Auth::user()){
    $data['allSubscriptions'] = $data['allSubscriptions'] = (Auth::user()->wasStripePlan()) ? Auth::user()->subscriptions : [];
}else{
    $data['allSbuscriptions'] = false;
}

Since you check if the user is logged in with isset, no error will be thrown and no need to try to catch one. Also unless you know what kind of error will be thrown, I'd just use the base Exception class on your catch block. Since it won't resolve the catch unless the Exception type matches. Since all of the types inherit from Exception, you'll catch the first one that comes up.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.