试图获得财产' id' laravel 5.6中的非对象

时间:2018-06-15 20:32:54

标签: php laravel object

你好我想知道我做错了什么我得到这个错误这里是我的控制器和视图

$invoice_specs = invoice::find($id);
$view=view('admin.invoices.pdf',compact('invoice_specs',$invoice_specs));

这里是我的观点

    <table class="table ">
                <thead>
                <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>description</th>
                </tr>
                </thead>
                <tbody>
                @foreach($invoice_specs as $invoice_spec)
                    <tr>
                        <td>{{$invoice_spec->id}}</td>
                        <td>{{$invoice_spec->title}}</td>
                        <td>{{$invoice_spec->description}}</td>
                    </tr>
                @endforeach
                </tbody>
            </table>

最后这里是我发票$ invoice_specs

#attributes: array:5 [▼
"id" => 3
"title" => "سومین فاکتور"
"description" => "سومین فاکتور"
"created_at" => "2018-06-12 21:31:57"
"updated_at" => "2018-06-12 21:31:57"]


 #original: array:5 [▼
    "id" => 3
    "title" => "سومین فاکتور"
    "description" => "سومین فاکتور"
    "created_at" => "2018-06-12 21:31:57"
    "updated_at" => "2018-06-12 21:31:57"
  ]

4 个答案:

答案 0 :(得分:1)

问题是您调用的静态find方法从数据库中检索数据,只返回单个模型而不是集合。因此,当您在视图中尝试将foreach与变量$invoice_specs一起使用时,它实际上并没有遍历模型集合。

Laravel's docs on Eloquent and retrieving single models中,您可以看到findfirst方法仅返回单个模型,您无法将其用于foreach循环。

This section of Laravel's docs解释了如何检索模型以及如何使用它们。我建议你先阅读:)

目前,如果要显示单个模型,可以执行的操作是摆脱视图中的foreach循环,在控制器中,您应该将变量invoice_specs重命名为invoice_spec

答案 1 :(得分:1)

您的invoice_specs是单个模型,您可能不想使用foreach对其进行迭代,您可以直接尝试在id上访问invoice_specs属性。

但是,您似乎想要查找一些发票,但是您使用find()primary key查找,在这种情况下,您只会得到一个或没有结果。

请提供更清晰的问题。

答案 2 :(得分:1)

你不应该在这里迭代结果。你应该在你的HTML

中这样做
<table class="table ">
 <thead>
  <tr>
     <th>id</th>
     <th>name</th>
     <th>description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
     <td>{{$invoice_specs->id}}</td>
     <td>{{$invoice_specs->title}}</td>
     <td>{{$invoice_specs->description}}</td>
  </tr>
 </tbody>
</table>

答案 3 :(得分:1)

不要在那里使用foreach循环,它不是集合。 只需立即使用$invoice_spec->id即可。就是这样。

我们对集合使用foreachforelse