浏览页面ID除了某些ID - laravel

时间:2015-03-02 21:33:45

标签: php laravel model-view-controller laravel-4

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

我使用了本教程: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]+');

1 个答案:

答案 0 :(得分:1)

一些建议:

您希望尝试将复杂的逻辑排除在您的视野之外。确定上一个/下一个ID并不是您的责任。这些值应该传入。

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

最后,就您的功能而言,您可能需要考虑将逻辑解析为产品模型上的方法。虽然,我不会使它成为模型范围方法,因为您返回的是值而不是查询对象。有点像:

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));
}