Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('App\MenuVariation');
    }

MenuVariation model

public function item()
    {
        return $this->belongsTo('App\MenuItem', '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).

like image 224
InvalidSyntax Avatar asked Oct 31 '15 20:10

InvalidSyntax


1 Answers

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.

like image 127
Kirill Fuchs Avatar answered Oct 06 '22 04:10

Kirill Fuchs