Get foreign key data based on shop id

Issue

I have two tables: shop and menu.

shop

$table->id();
$table->string('name');

menu

$table->id();
$table->string('name');
$table->unsignedBigInteger('shop_id');
$table->foreign('shop_id')->references('id')->on('shop')->onDelete('cascade');

I need to print out menus name when you enter shop id (for example url /shop{id})

I have controller but i’m sure it’s not the correct code.

MeniuController

public function menu($id)
{
    $men = shop::select('name')->where('id', $id)->get();
    return view('meniu', compact('men')); 
}

Solution

Controller method:

public function menu($id)
{
   return view('menu', [
      'menus' => Menu::where('shop_id', $id)->get(),
   ]);
}

Blade template:

@foreach($menus as $menu)
   <div>{{ $menu->name }}</div>
@endforeach

Answered By – Yami

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published