此集合实例上不存在属性 [title]Property [title] does not exist on this collection instance

假设我们正在尝试使用控制器文件中的以下代码将数据传递给视图:

public function index()
{
    $about = Page::where('page', 'about-me')->get(); //id = 3

    return view('about', compact('about'));
}

当我们尝试显示如下所示的代码时,

@section('title')
    {{$about->title}}
@stop

@section('content')
    {!! $about->content !!}
@stop

我们会收到错误消息:

此集合实例上不存在属性 [title]。(查看:E:\laragon\www\newsite\resources\views\about.blade.php)

当我们使用get()时,我们会得到一个集合。在这种情况下,我们需要对其进行迭代以获取属性:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

或者我们可以通过它的索引获取其中一个对象:

{{ $collection[0]->title }}

或者从集合中获取个对象:

{{ $collection->first() }}

当我们使用find()first()获得一个对象时,我们可以通过简单的方式获得属性:

{{ <span class="hljs-variable">$object</span>->title }}

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/115141.html<

(0)
运维的头像运维
上一篇2025-02-18 00:36
下一篇 2025-02-18 00:37

相关推荐

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注