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条)

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败