View Composer - how to pass complete collective through ?

Published 6 days ago by gr8h8m

So i'm trying to pass data to my sidebar on all pages for menu

Menu class:

class Menus extends Model {

    protected $table = 'menus'; protected $fillable = ['title','parent_id'];

    public function parent() {

         return $this->hasOne('App\Menus', 'id', 'parent_id')->orderBy('order'); 
    }

    public function children() { 
        return $this->hasMany('App\Menus', 'parent_id', 'id')->orderBy('order'); 
    }
 }

using ComposerServiceProvider to pass data to View

view()->composer('backend.includes.sidebar', function ($view) {

         $view->with('menus', \App\Menus::where('parent_id', 0)->orderBy('order')->get());

});

Ger error: Property [children] does not exist on this collection instance

How can i pass a complete collective (all menu and submenu items from database) to a view using a view composer so the menu appears on all pages

have got it working fine on one page, but that was not using a view composer to pass data.

Best Answer (As Selected By gr8h8m)
gr8h8m

Oops just spotted my error, odd how reading code somewhere else you spot the obvious simple mistake :)

backend.includes.sidebar

should be frontend.includes.sidebar

all works now :)

gr8h8m
gr8h8m
6 days ago (11,250 XP)

Oops just spotted my error, odd how reading code somewhere else you spot the obvious simple mistake :)

backend.includes.sidebar

should be frontend.includes.sidebar

all works now :)

Snapey
Snapey
6 days ago (705,395 XP)

Looks fine to me

dont forget that in the view, $menus is a collection of Menu model so you cannot call $menus->children

i dont know if this is what is happening because you don't show the file that actually throws the error

gr8h8m
gr8h8m
6 days ago (11,250 XP)

that was the reason for the error. but in view i'm looping through $menus first then i get children

View is:

@foreach($menus as $category)
        @if ((count($category->children) > 0) AND ($category->parent_id === 0))
            <li class="treeview">
                <a href="#"><i class="fa fa-list"></i><span>{{ $category->title }}</span>
                    <i class="fa fa-angle-down pull-right"></i>
                </a>
                <ul class="treeview-menu" >
                @foreach($category->children as $category)
                    @include('frontend.includes.partials.submenu', $category)
                @endforeach
                </ul>
            </li>
        @else
            <li class=""><!-- route('menu', ['slug' => $category->slug]) -->
                <a href=""><i class="fa fa-list"></i><span>{{ $category->title }}</span></a>
            </li>
        @endif
        @endforeach
Snapey
Snapey
5 days ago (705,395 XP)

my response was before I had sight of your reply.

Please sign in or create an account to participate in this conversation.