此集合实例上不存在属性 [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()获得一个对象时,我们可以通过简单的方式获得属性:

{{ $object->title }}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容