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

查看:90
本文介绍了该集合实例上不存在属性[title]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Laracasts的视频:基本模型/控制器/查看工作流程.

I am following Laracasts' videos: Basic Model/Controller/View Workflow.

我有一张桌子,上面保存着联系方式.

I have a table holds contact information.

CREATE TABLE `about` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

我正在尝试使用控制器文件中的以下代码传递数据以进行查看:

I am trying to pass data to view using the following code in the controller file:

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

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

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

When I try to show the code as shown below,

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

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

我看到一条错误消息:

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

Property [title] does not exist on this collection instance. (View: E:\laragon\www\newsite\resources\views\about.blade.php)

但是,如果我更改控制器文件中的检索方法,它将起作用.

But if I change the retrieving method in the controller file, it works.

public function index()
{
    $about = Page::find(3);

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

在第一种情况(where()->get())中使用dd($about)时,数据由数组封装.在第二种情况下(find(3)),它将按预期显示数据.

When I use dd($about) in the first case (where()->get()) the data is encapsulated by an array. In the second case (find(3)) it displays data as expected.

我在做什么错?

推荐答案

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

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

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

或者您也可以通过索引获得其中一个对象

Or you could just get one of objects by it's index:

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

或从集合中获取第一个对象:

Or get first object from collection:

{{ $collection->first() }}

使用find()first()时,您会得到一个对象,因此可以通过以下简单方式获得属性:

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

这篇关于该集合实例上不存在属性[title]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆