浏览除特定id之外的页面id-laravel


Navigate through page ids except certain ids - laravel

我有一个商店,您可以通过单击按钮导航到下一个/上一个产品。

我使用了本教程: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的产品,只是没有下一个/上一个按钮。

我的路线:

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]+');

几个建议:

你想尽量把复杂的逻辑排除在你的视野之外。您的视图不负责确定上一个/下一个id。这些值应该传入。

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

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

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));
}
相关文章: