无法将 stdClass 类型的对象用作数组 Laravel 错误

Cannot use object of type stdClass as array Laravel Error

因此,当我尝试使用数组

从数据库中检索数据时,出现此错误 "Cannot use object of type stdClass as array"

我的控制器

public function openingPage($id) {

      $this->getCaseData($id);

      return view('caseopener', ['cases' => $cases]);

    }

    private function getCaseData($id) {
        $cases = DB::table('cases')->where('id', $id)->first();
        $data = @$cases[0] ? $cases[0] : array();
        if(isset($data->items)) {
            $data->items = json_decode($data->items, true);
        }

        $this->data = $data;
    }

我还看到问题来自这一行:

 $data = @$cases[0] ? $cases[0] : array();

您没有为 return 视图中的 $cases 变量分配任何内容。所以在这一行中:

 $this->getCaseData($id);

您调用下面设置 $this->data 的函数,但它不会在 openingPage() 方法中的任何位置分配 $case。然后,当您 return 带有名为 'cases' 的变量的视图时,它没有任何内容可发送:

return view('caseopener', ['cases' => $cases]);

分配变量 $cases: $cases = $this->getCaseData($id); 或 return class 变量:

return view('caseopener', ['cases' => $this->data]);