浏览除某些 ID 之外的页面 ID - laravel

Navigate through page ids except certain ids - laravel

我有一家商店,您可以通过单击按钮导航到 next/previous 产品。

我使用了这个教程:http://laravel-tricks.com/tricks/get-previousnext-record-ids

我的问题是我想跳过某些产品的 4 个 ID。我根本不想显示这些。

我该怎么做?

这是我的尝试:

@unless($product->id == 17 || $product->id == 18 || $product->id == 20 || $product->id == 22  )

    <?php  
        $previous = Product::where('id', '<', $product->id)->max('id');

        $next = Product::where('id', '>', $product->id)->min('id');
    ?> 

    <a href="{{URL::to('products/'.$previous)}}" id="prevProd"><i class="fa fa-angle-left"></i></a>
    <a href="{{URL::to('products/'.$next)}}" id="nextProd"><i class="fa fa-angle-right"></i></a>
@endunless 

我应该在我的路线中这样做吗?这是行不通的。它仍然显示具有这些 ID 的产品,只是没有 next/previous 按钮。

我的路线:

Route::get('products/{id}', function($id)
{
    $oProduct = Product::find($id);

    return View::make('singleproduct')->with('product', $oProduct)->with("cart",Session::get("cart"));

})->where('id', '[0-9]+');

一些建议:

您想尝试将复杂的逻辑排除在您的视野之外。确定 previous/next id 不是您的视图的责任。应传入这些值。

此外,您可能需要考虑将路由中的逻辑移动到控制器中。所有路由应该做的是指向应该是 运行 的 controller/method。实际处理任何逻辑(在发送应用程序的地方之外)不是路由的工作。

最后,就您的功能而言,您可能需要考虑将逻辑提取到产品模型的方法中。不过,我不会将其设为模型作用域方法,因为您返回的是一个值而不是查询对象。大致如下:

public function getNextId(array $except = null) {
    $query = $this->where('id', '>', $this->id);
    if (!empty($except)) {
        $query->whereNotIn('id', $except);
    }
    return $query->min('id');
}

public function getPreviousId(array $except = null) {
    $query = $this->where('id', '<', $this->id);
    if (!empty($except)) {
        $query->whereNotIn('id', $except);
    }
    return $query->max('id');
}

现在,在您的路线(或控制器,如果您移动到那个路线)中,您可以:

function($id) {
    $excludeIds = array(17, 18, 20, 22);
    // you may want some logic to handle when $id is one of the excluded
    // ids, since a user can easily change the id in the url
    $oProduct = Product::find($id);
    return View::make('singleproduct')
        ->with('product', $oProduct)
        ->with('cart', Session::get('cart'))
        ->with('previous', $oProduct->getPreviousId($excludeIds))
        ->with('next', $oProduct->getNextId($excludeIds));
}