繁体   English   中英

产品页面上的上一个和下一个产品链接

[英]prev and next product links on Product page

我有 4 个子类别级别的产品目录

路线/ web.php

Route::get('/products/{level2?}/{level3?}/{level4?}',   'ProductController@showIndex');
Route::get('/products/{level2?}/{level2prod?}/{level3?}/{level3prod?}/{level4?}/{level4prod?}',     'ProductController@showProduct');

第一条路线是显示具有相应产品的类别,这些类别是当前类别的子项。 在 Product 和 Category 模型之间存在多对多关系$this->belongsToMany 我有 category_product 数据透视表。

ProductController 中的 showProduct 函数接收$request ,我从$request->path() 中提取最后 2 个段。 最后一个路径段等于当前产品 sef - 这是加载产品页面的最重要信息。 前一个路径段等于父类别 sef。 这需要知道我们现在位于哪个类别下。 因为一个产品可能属于多个类别,我们不知道当前产品页面是如何加载的。 在这种情况下,我使用$category来加载这样的面包屑

Home > Products > Category level 2 > Category level3 > Category level4
    public function showProduct(Request $request) {
        $parent = '';
        $categorysef = '';
        // we need only last part of uri after last slash
        if ( strrpos($request->path(), '/') !== false ) {
            $sef = substr($request->path(), strrpos($request->path(), '/') + 1);
            $parent = substr($request->path(), 0, strrpos($request->path(), '/') );
            if ( strrpos($parent, '/') !== false ) {
                $categorysef = substr($parent, strrpos($parent, '/') + 1);
            }
            else {$categorysef = $parent;}
        } else {
            $sef = $request->path();
        }

        $item     = Product::whereSef($sef)->firstorfail();
        $previous = Product::where('id', '<', $item->id)->orderBy('id', 'desc')->first();
        $next     = Product::where('id', '>', $item->id)->orderBy('id', 'asc')->first();
        $category = Category::whereSef($categorysef)->firstorfail();

        return view('product.item')
                    ->withItem($item)
                    ->withPrevious($previous)
                    ->withNext($next)
                    ->withCategory($category);
    }

我无法理解的一件事是如何过滤$previous$next以仅包含属于当前类别的值。

找到解决方案!

@if ( !empty($previous) and in_array( $category->id, $previous->category->pluck('id')->toArray()) )
   <li><a href="{{ $previous->sef }}">← Prev</a></li>
@endif

下一个链接的相同代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM