A
A
Analka2021-04-08 09:41:16
Laravel
Analka, 2021-04-08 09:41:16

How to display categories and products in Laravel?

there is a Category model

class Category extends Model
{
    use HasFactory;

    protected $table = 'categories';

    public function products()
    {

        return $this->hasMany(Product::class);
    }
}


and Product model

class Product extends Model
{
    use HasFactory;

    protected $table = "products";

    public function category() {

        return $this->belongsTo(Category::class, 'category_id');
        
    }
}


how to display categories and all products for them (such a moment that you need to display only those categories that have products)

the output is as follows:
-Название категории
---Товар 1
---Товар 2
---Товар 3
-Название категории 2
---Товар 4
---Товар 5
---Товар 6


I tried this, but it doesn't show the goods

$column = [
            'id',
            'name',
            'path',
            'image',
            'slug',
        ];

        $columnProduct = [
            'id',
            'name',
            'path',
            'image',
            'slug',
        ];

        $categories = Category::select($column)
            ->with(['products' => function($query) use ($columnProduct, $shopId) {
                $query->select($columnProduct);
                $query->where('shop_id', $shopId);
            }])
            ->where('is_published', 1)
            ->get();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question