4 months ago

How to access eager loaded records from single model

Posted 4 months ago by naykel

I am trying to work out how to access eager loaded when only dealing with a single record.

Here I am querying the database to return a menu named ‘main’ and eager loading the links related to this menu.

$menu =  Menu::where('name', 'main')->with('links')->get();

I want to loop throught and display the links but I can not figure out ho to do it without looping through the single menu first which seems counter productive because there is only one menu.

@foreach ($menu as $m)
    @foreach ($m->links as $l)
        {{ $l->name }}

I have tried the following but it says that links in not in the collection.

@foreach ($menu->links as $menu)
    {{ $menu->name }}

Is there a better way?

Thanks in advance.

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