php - 将对象从 Controller 传递到 View

标签 php laravel laravel-5

我正在尝试将一组行从 Controller 传递到 View :

$items = Items::where('group', '=', $group);
return view('listing', [
    "group" => $group,
    "exists" => $items->exists(),
    "items" => $items->get(),
]);

在我看来:

@if (!$exists)
    Nothing
@else
<ul id="items">
@foreach ($items as $item)
    <li>
        {{ $item->user }}: {{ $item->content }}
    </li>
@endforeach
</ul>
@endif

该 View 仅返回 1 项。 $items 的长度为 1。如果我在 Controller 中 count($items),我会得到预期的项目数。

如何将对象从 Controller 传递到我的 View ?


我的最终解决方案:

Controller

$items = Items::where('group', '=', $group);
return view('listing', [
    "group" => $group,
    "items" => $items->get(),
    "exists" => $items->exists(), // Important! Has to go after!
]);

在我看来:

@if (!$exists)
    Nothing
@else
<ul id="items">
@foreach ($items as $item)
    <li>
        {{ $item->user }}: {{ $item->content }}
    </li>
@endforeach
</ul>
@endif

最佳答案

问题是在调用 get() 之前调用了 exists()。对 exists() 的调用正在修改您的查询构建器以向其添加 limit(1)。因此,当您在 exists() 之后调用 get() 时,查询构建器仍然附加了 limit(1)

您更新的解决方案有效,因为您删除了对 exists() 的调用。

但是,对 get() 的调用仍应在 Controller 中完成。 View 只能传递对象集合,而不是查询生成器。

关于php - 将对象从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577232/

相关文章:

laravel - 如何将 Laravel 5 session 更改为 redis

php - 如果变量为空或未赋值,则将值放入函数中不起作用

PHP 二维数组到 MySQL 数据库

php - 正确的 PHP 404 重定向?

php - wamp 上的 Laravel 4 htaccess vhost NotFoundHttpException 问题

php - Laravel Eloquent 有很多关系

php - 我的 ask.php 语法有什么问题?

php - 在 mysql (laravel) 中使用单独的主机进行读写有什么好处?

php - 在列 Laravel 5.4 中应用字符串函数

php - 如何在 laravel 的服务提供者中检索 session 数据?