dongren1977 2019-01-18 19:46
浏览 75
已采纳

Laravel在null上调用成员函数

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?

  • 写回答

2条回答 默认 最新

  • doudiemei2013 2019-01-18 20:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line