无法通过ViewComposer将Collection传递给视图

时间:2016-08-14 07:49:30

标签: php laravel laravel-5.2

我有一个视图作曲家:

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use App\Models\FloatingMenu;

class FloatingMenuComposer {

  protected $floatingMenu;

  public function __construct()
   {
       // Dependencies automatically resolved by service container...
       $this->floatingMenu = FloatingMenu::all();
   }


    public function compose(View $view) 
    {
       $floatingMenuItems = null;
       foreach($this->floatingMenu as $menu){
         if ($view->getName() == $menu->page) {
           $floatingMenuItems = $menu->floatingMenuItems()->get();
         }
       }
       $view->with('floatingMenuItems' , $floatingMenuItems);
    }
}

如果我在视图中转储$ floatingMenuItems变量,我会得到null。但是,如果我在compose()函数中转储$ floatingMenuItems变量,它肯定包含一组数据。

如果我卖掉了:

$view->with('floatingMenuItems' , $floatingMenuItems);

使用:

$view->with('floatingMenuItems' , "Random String");

然后它在我转储$ floatingMenuItems变量时打印出视图中的随机字符串。因此,由于某种原因,它不允许我通过视图编辑器将集合传递给我的视图。

我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

在if语句中更改返回视图的位置。(因为它只执行一次)

public function compose(View $view) 
    {
       $floatingMenuItems = collect(); //remove this
       foreach($this->floatingMenu as $menu){
         if ($view->getName() == $menu->page) {
           //$floatingMenuItems = $menu->floatingMenuItems()->get();
           $view->with('floatingMenuItems' , $menu->floatingMenuItems()->get());
         }
       }       
    }

答案 1 :(得分:0)

在我看来:
1.你在compose()函数中转储$ floatingMenuItems变量的位置是什么?在foreach或foreach外面?
你得浮动菜单后你应该打破foreach 试试吧!