如何在不使用 if 语句和 show 文件中的 foreach 的情况下将数据传递给视图?

当我观看 youtube Laravel From Scratch [第 6 部分] - 使用 Eloquent 获取数据时,我看到他在不使用 if 语句和 foreach 的情况下传递数据以查看,我已经尝试过但没有工作


public function show(todo $todo)

{

 $todo=todo::find($todo);

 return view('demo')->with('todo',$todo);

}

我的观点没有 if 语句和 foreach


    @extends('layouts.app')

@section('content')

    {{$todo->note}}

@endsection

我在使用 if 语句和 foreach 时的看法


@extends('layouts.app')

@section('content')

@if (count($todo) > 0)

    @foreach ($todo as $item)

        {{$item->note}}

    @endforeach

@endif


@endsection

我收到一个错误


Property [note] does not exist on this collection instance

https://www.youtube.com/watch?v=emyIlJPxZr4&list=PLillGF-RfqbYhQsN5WMXy6VsDMKGadrJ-&index=6


慕标琳琳
浏览 101回答 2
2回答

慕的地6264312

该属性不存在的原因是因为结果是一个集合而不是一个数组(在操作注释中找到)所以你试图note从一个看起来像这样的集合中获取:[&nbsp; {&nbsp; &nbsp; "id":1,&nbsp; &nbsp; "note":"to do one",&nbsp; &nbsp; "created_at":"2020-04-12 08:25:00",&nbsp; &nbsp; "updated_at":"2020-04-13 07:20:54",&nbsp; &nbsp; "description":"description for todo one"&nbsp; }]当您打电话时,$todo->note您正在搜索此行:[&nbsp; { # <-- You're searching this line&nbsp; &nbsp; "id":1,&nbsp; &nbsp; "note":"to do one",&nbsp; &nbsp; "created_at":"2020-04-12 08:25:00",&nbsp; &nbsp; "updated_at":"2020-04-13 07:20:54",&nbsp; &nbsp; "description":"description for todo one"&nbsp; }]所以你的代码返回一个集合而不是一个数组。一个数组看起来像这样:{ # <-- Starts with open curly bracket instead of open square bracket&nbsp; "id":1,&nbsp; "note":"to do one",&nbsp; "created_at":"2020-04-12 08:25:00",&nbsp; "updated_at":"2020-04-13 07:20:54",&nbsp; "description":"description for todo one"}你需要弄清楚它为什么要发送一个集合。从您的代码来看,我发现了一个潜在的问题:public function show(todo $todo) # <- What is 'todo $todo'?{&nbsp;$todo=todo::find($todo);&nbsp;return view('demo')->with('todo',$todo);}什么是todo $todo,你在某处调用 show 函数?默认情况下,Laravel 通过网络路由发送该 ID。所以尝试将其更新为:public function show($id) #<-- change this to '$id'{&nbsp;$todo = Todo::find($id); #<-- Change this to '$id'&nbsp;return view('demo')->with('todo',$todo);}让我知道是否可以解决问题。编辑:你真的需要修正你的大写。

智慧大石

$todo=todo::find($todo)->first();
打开App,查看更多内容
随时随地看视频慕课网APP