【问题标题】:Data getting lost while passing from controller to view in Laravel从控制器传递到 Laravel 中的视图时数据丢失
【发布时间】:2014-09-13 16:33:36
【问题描述】:

在我的一个控制器中,我将从 Eloquent 查询获得的结果传递给视图。但是无论我如何将结果传递给视图,我都没有在视图中得到结果。

控制器:

class ProductCategoriesController extends BaseController
{

    public function __construct()
    {
        parent::__construct();

        // Add location hinting for views
        View::addNamespace('product-categories', app_path() . "/MyVendor/ProductsManager/Views/admin/product-categories");
    }

    public function index()
    {
        $categories = ProductCategory::all();

        return View::make('product-categories::index')
                    ->with('title', 'All Product Categories')
                    ->with('categories', $categories);
    }

    ...
}

如果我在 index 控制器中查看 dd 的值 $categories,我会得到正确的 Eloquent 集合,如下所示:

object(Illuminate\Database\Eloquent\Collection)[655]
  protected 'items' => 
    array (size=1)
      0 =>
         object(MyVendor\ProductsManager\Models\ProductCategory)[653]
          protected 'table' => string 'product_categories' (length=18)
          protected 'guarded' => ...

但如果我在 index 视图中 dd $categories 的值,我会得到一个空的 Eloquent 集合,如下所示:

object(Illuminate\Database\Eloquent\Collection)[655]
  protected 'items' => 
    array (size=1)
      0 => null

我在其他控制器中也采用了类似的方法,它们运行良好。我不知道这个控制器有什么问题。我使用 Laravel 已经有一段时间了,以前从未遇到过这个问题。也许我遗漏了一些东西,或者最近的软件包更新有问题。不管它是什么,它让我发疯。关于问题可能是什么的任何想法?

附:我正在使用Laravel Framework version 4.2.6

【问题讨论】:

  • 您也可以发布您的视图和模型代码吗?
  • 也许你用相同的变量名调用View::composer,如果你将categories重命名为别的名字呢?
  • 你可能有一些其他全局绑定到这个视图的这个名称。重命名绑定。
  • 你试过View::make('product-categories::index', ['title' => 'All Product Categories','categories' => $categories) 吗?

标签: laravel laravel-4 eloquent


【解决方案1】:

我终于弄清楚了问题所在。我使用robclancy/presenter 包来包装和渲染视图中的对象。为此,模型必须实现PresentableInterface 接口。实现接口要求方法具有getPresenter 方法。我在模型中添加了getPresenter 方法,但我忘记从该方法返回演示者。让演讲者回归解决了这个问题。

getPresenter方法里面的代码是我忘记写的代码。

public function getPresenter()
{
    return new ProductCategoryPresenter($this);
}

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2017-01-29
    • 2015-07-25
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多