x69 x69 - 1 month ago 16
Javascript Question

Laravel : How to show dependent variable on tab

I have two tables , categories and product.Each category has id and name. Each product has id, name and category id. Now I want to load the data on each tab when a user click on specific category_id.so related product will be shown on each category tab. I have tried but couldn't get the solution.

Category Model:

class Category extends Model
{
public function products()

{
return $this->hasMany('App\Product');
}
}


Product Model:

class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}

}


Here is my controllers:

public function gettestItem() {
$categories = Category::with('products')->get();
return view('products', compact('categories'));
}


Here is the view :

<div class="container">
<div id="content">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
@foreach ($categories as $category)
<li><a href="#{{$category->id}}" data-toggle="tab" >{{$category->name}}</a></li>
@endforeach
</ul>

<div id="my-tab-content" class="tab-content">
@foreach($categories as $category)
@foreach($category->products as $product)
<div class="tab-pane " id="{{$category->id}}">
{{$product->name}}
</div>
@endforeach
@endforeach
</div>
</div>
</div>


Here is the route:

Route::get('/testItem',[
'uses'=>'ItemController@gettestItem',
'as'=>'testItem'
]);


if anyone could help me solve the problem will be appreciated.

Answer

If you have defined your schema and relations properly then function should be as:

public function gettestItem() {
  $categories = Category::with('products')->get();
  return view('products', compact('categories'));
}

then you can access product of each category as:

foreach ($categories as $category) {
    $category->product; // gives all products corresponding to $category
}

And also please read the Docs

Update

Your 2nd foreach should be as:

<div id="my-tab-content" class="tab-content">
  @foreach($categories as $category)
    <div class="tab-pane" id="{{$category->id}}">
      @foreach($category->products as $product) 
      <div>
          {{$product->name}}
      </div>  
      @endforeach
    </div>
  @endforeach
</div>

You can also use following code to get only those categories which have corresponding products:

$categories = Category::has('products')->with('products')->get();