Skip to content
Advertisement

Laravel findOrFail with related data?

In my Menu controller I have a method which should display the specified record and all its children.

I have two models: MenuItem and MenuVariation, My items will have many variations as outlined in my methods:

MenuItem model

public function variant()
    {
        return $this->hasMany('AppMenuVariation');
    }

MenuVariation model

public function item()
    {
        return $this->belongsTo('AppMenuItem', 'menu_item_id');
    }

Now in my controller I have the following method:

public function show($id)
{
    $item = MenuItem::findOrFail($id);
    return $item;
}

…which currently only shows the item record but not its variations, so I have changed the code like this…

public function show($id)
{
    $item = MenuItem::findOrFail($id)->with('variant')->get();
    return $item;
}

but this oddly return ALL items and their variations.

Could someone help me get this working as desired? I would like to still utilise FindOrFail on the Item record, but it should also retrieve any variants (if found).

Advertisement

Answer

findOrFail will initiate the query, so you want to switch the order and put with in-front of it. Then use findOrFail. See Below:

public function show($id)
{
    $item = MenuItem::with('variant')->findOrFail($id);
    return $item;
}

There is also no need for get when you do that.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement