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

时间:2020-01-03 18:48:55

标签: php laravel pagination

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

routes / web.php

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

第一个路线是显示带有相应产品的类别,这些产品属于当前类别。 在产品模型和类别模型之间,存在许多对很多的关系 $ this-> belongsToMany 。我有category_product数据透视表。

ProductController中的

showProduct函数收到 $ request ,我从 $ request-> path()中提取了最后两个段。 最后一个路径段等于当前产品安全系数-这是加载产品页面最重要的信息。上一个路径段等于父类别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 以仅包含属于当前类别的值。

1 个答案:

答案 0 :(得分:0)

找到解决方案!

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

下一个链接的代码相同。