Sean Routledge Sean Routledge - 3 months ago 5
PHP Question

Unable to pass Collection to views via ViewComposer

I have a view composer:

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);
}
}


If I dump the $floatingMenuItems variable in the view I get null. However If I dump the $floatingMenuItems variable in the compose() function it definitely contains a collection of data.

If I swop out:

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


with:

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


then it prints out the random string in the view when I dump the $floatingMenuItems variable. So for some reason it is not allowing me to pass a collection to my view via the view composer.

How can i get around this?

Answer

Change your placement of returning view inside if statement.(since it is executing only once)

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());
         }
       }       
    }
Comments