1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Services\LiquidRenderer;
- use App\Models\DistProduct;
- use App\Models\DistProductCategory; // 引入分类模型
- class ProductController extends Controller
- {
- protected $liquidRenderer;
- public function __construct(LiquidRenderer $liquidRenderer)
- {
- $this->liquidRenderer = $liquidRenderer;
- }
- /**
- * Display a listing of the products.
- *
- * @return \Illuminate\Http\Response
- */
- // public function index()
- // {
- // $products = Product::paginate(10); // 每页显示10个产品
- // return $this->liquidRenderer->render('products.index', ['products' => $products]);
- // }
- public function category($slug)
- {
- // $products = DistProduct::paginate(10); // 每页显示10个产品
- // return $this->liquidRenderer->render('products_categories.liquid', ['products' => $products]);
- // 获取分类信息
- $category = DistProductCategory::findOrFail($slug);
- // 获取分类下的所有产品,并按 is_pinned 排序,然后进行分页
- $products = DistProduct::where('category_id', $category->id)
- ->where('dist_id', getDistId())
- ->where('enabled', 1)
- ->with('images') // Eager load images
- ->orderBy('is_pinned', 'desc') // 按 is_pinned 降序排序
- ->paginate(12);
- // 创建分页数据结构
- $paginator = [
- 'previous_page' => $products->previousPageUrl() ? true : false, // 是否有上一页
- 'previous_page_url' => $products->previousPageUrl(), // 上一页的 URL
- 'next_page' => $products->nextPageUrl() ? true : false, // 是否有下一页
- 'next_page_url' => $products->nextPageUrl(), // 下一页的 URL
- 'current_page' => $products->currentPage(), // 当前页
- 'total_pages' => $products->lastPage(), // 总页数
- 'pages' => range(1, $products->lastPage()), // 页码数组
- 'page_url' => array_combine(
- range(1, $products->lastPage()),
- array_map(fn($page) => $products->url($page), range(1, $products->lastPage()))
- ), // 每页的 URL
- ];
- // 渲染模板并传递数据
- return $this->liquidRenderer->render('products_categories.liquid', [
- 'category' => $category, // 分类名称
- 'products' => $products, // 分类下的产品
- 'paginator' => $paginator, // 分页信息
- ]);
- }
- /**
- * Display the specified product.
- *
- * @param int $id
- * @return \Illuminate\Http\Response
- */
- public function detail($id)
- {
- $product = DistProduct::getProduct($id);
- return $this->liquidRenderer->render('products_detail.liquid',
- [
- 'product' => $product,
- 'csrf_token' => csrf_token()
- ]);
- }
- }
|