I am using Laravel 5.8 with Laravel-nestedset for my category model and I have a product model.
I am successfully creating nested categories and displaying them properly, but when I get to a category that has a product, I want to product(s) that belong to the current category to display--the code below with show products, but not in the category that they belong to. This is pretty standard stuff I imagine, but I can't seem to figure it out.
Category.php
<?php
namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use \Spatie\Tags\HasTags;
use HasSlug;
use NodeTrait;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
public function getRouteKeyName()
{
return 'slug';
}
}
Product.php
<?php
namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use \Spatie\Tags\HasTags;
use HasSlug;
protected $dates = [
'published_on',
];
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
public function getRouteKeyName()
{
return 'slug';
}
public function category()
{
return $this->belongsTo(Category::class);
}
}
CategoryController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Product;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get()->toTree();;
return view('categories.index', compact('categories'));
}
public function show(Category $category)
{
$products = Product::with('category')->whereIn('category_id', $category)->get();
return view('categories.show', compact('category', 'products'));
}
}
show.blade.php (this is the category show template and where I want the products to show)
...
@if (count($category['children']) > 0)
@foreach($category['children']->chunk(3) as $chunk)
<div class="row">
@foreach($chunk as $category)
<div class="col-md-4" style="margin-bottom: 2rem">
<div class="feature-box center media-box fbox-bg">
<div class="fbox-media">
<a href="/">
<img class="image_fade"
src="https://*****.s3-us-west-1.amazonaws.com/"
alt="Featured Box Image"
style="opacity: 1;"></a>
</div>
<div class="fbox-desc">
<h3></h3>
<span><a href="">Learn More</a></span>
</div>
</div>
</div>
@endforeach
</div>
@endforeach
@endif
@if(count($products) > 0)
@foreach($products as $product)
@endforeach
@endif
...
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire