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?

Aaron
  • 4,380
  • 19
  • 85
  • 141
  • 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. – N Mahurin Jan 18 '19 at 19:50

2 Answers2

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.

Rafay Hassan
  • 740
  • 8
  • 23
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.

N Mahurin
  • 1,406
  • 10
  • 18