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

查看:25
本文介绍了此集合实例上不存在属性 [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:laragonwww ewsite esourcesviewsabout.blade.php)

Property [title] does not exist on this collection instance. (View: E:laragonwww ewsite esourcesviewsabout.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'));
}

当我在第一种情况下使用 dd($about) 时(where()->get()),数据被一个数组封装.在第二种情况 (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天全站免登陆