You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel电商站按分类ID查询产品时页面样式异常求助

Fixing Your Category Product Query Issue

Hey Ahmed, I can spot the immediate problem in your controller code that's causing the broken layout when passing a category_id—let's break it down and fix it!

1. The Critical Where Clause Mistake

Your query is filtering products by product_id instead of category_id! That means when you pass a category ID, it's looking for products whose product ID matches the category ID—which almost certainly returns no results. Empty data makes your page layout collapse because there's no product content to fill the expected HTML structure.

Here's the corrected query part:

$category_by_product = DB::table('tbl_products')
    ->join('tbl_category', 'tbl_products.category_id', '=', 'tbl_category.category_id')
    ->join('tbl_manufacture', 'tbl_products.manufacture_id', '=', 'tbl_manufacture.manufacture_id')
    ->select('tbl_products.*', 'tbl_category.category_name', 'tbl_manufacture.manufacture_name')
    // Fixed: filter by category_id, not product_id
    ->where('tbl_products.category_id', $category_id)
    ->limit(6)
    ->get();

2. Optional Improvements to Avoid Future Issues

  • Handle Empty Results: Add a check for empty data to show a friendly message instead of a broken layout:
    if ($category_by_product->isEmpty()) {
        return view('Pages.cate')->with('no_products', 'No products found in this category.');
    }
    
  • Simplify View Passing: You can clean up the view return logic a bit (your current way works, but this is more readable):
    return view('layouts.new', [
        'cate' => view('Pages.cate')->with('category_by_product', $category_by_product)
    ]);
    
  • Use Laravel Models (Recommended): If you create Eloquent models for Product, Category, and Manufacture, you can use relationships to make this query way cleaner. For example, define a category() relationship on the Product model, then query like:
    $category_by_product = Product::with(['category', 'manufacture'])
        ->where('category_id', $category_id)
        ->limit(6)
        ->get();
    

This should fix your query, return the correct products for the category, and get your page layout back to normal!

内容的提问来源于stack exchange,提问作者Ahmed Rimon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:54:15