在laravel按价格订购产品的问题

时间:2017-07-18 08:06:04

标签: php laravel laravel-5 laravel-5.2 laravel-5.3

我想按价格订购产品,一个链接从低到高,另一个从高到低, 但是,在我点击“从低到高”或“从高到低”后,订单不会改变,它会停留在同一页面上,但网址会发生变化。

这是控制器中的功能:

public function products(Request $request, $category_url, $sort= 'ASC')
{
    Product::getProducts($category_url, self:: $data);

    if ( $category1 = Categorie::where('url', '=', $category_url)->first() ) {

        $products = Product::where('categorie_id', $category1->getAttribute('id'))->orderBy('price', $sort)->get();

        return view('content.products', self::$data , compact('products', 'sort')); 
    }
}

这是路线:

  Route::get('shop/{category_url}/sorting-{sort?}', 'ShopController@products');

这些是视图中的链接,视图是content.products

  <a href="  {{ url('shop/'.$category['url'].'/sorting-asc')}}" style="color:black"> High to low</a> |
  <a href="  {{ url('shop/'.$category['url'].'/sorting-desc')}}" style="color:black">Low to high</a>

模特:

class Product extends Model {


static public function getProducts($category_url, &$data){

    $data['products']=$data['category']=[];


    if ($category=Categorie::where('url','=', $category_url)->first()){

        $category= $category->toArray();
        $data['category']=$category;
        $data['title']=$data['title']. ' | ' . $category['title'];


        if ($products=Categorie::find( $category['id'])->products){

            $data['products']= $products->toArray();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在你的控制器中试试这个:

if ( $category1 = Categorie::where('url', '=', $category_url)->first() ) {

    $products = Product::where('categorie_id', $category1->getAttribute('id'));
    $products = strtolower($sort) == 'asc' ? $products->orderBy('price'):$products->orderByDesc('price');
    $products = $products->get();

    return view('content.products', self::$data , compact('products', 'sort')); 
}