如何订购Laravel从高到低,从低到高的产品 - 按此代码的价格?我得到了所有的默认演示文稿,但我想添加2个链接来制作问题字符串,所以只有当我点击它们时,产品将被订购,如从高到低或从低到高 - 其他明智的,当它没有点击任何链接时默认排序 - DESC或ASC 这是按顺序的代码:MODEL CONTROLLER HTML:
static public function getProducts($url_category, &$data) {
$data['products'] = [];
if ($category = Categorie::where('url', '=', $url_category)->first()) {
$category = $category->toArray();
$data['title'] = $data['title'] . $category['title'];
$data['url_category'] = $url_category;
if ($products = Categorie::find($category['id'])->products) {
$data['products'] = $products->toArray();
}
}
}
function __construct() {
parent::__construct();
$this->middleware('adminAuth');
}
public function index() {
self::$data['products'] = Product::all()->toArray();
return view('cms.products', self::$data);
}
public function create() {
self::$data['categories'] = Categorie::all()->toArray();
return view('cms.add_product', self::$data);
}
public function store(ProductRequest $request) {
Product::save_new($request);
return redirect('cms/products');
}
public function show($id) {
self::$data['product_id'] = $id;
return view('cms.delete_product', self::$data);
}
public function edit($id) {
self::$data['categories'] = Categorie::all()->toArray();
self::$data['product'] = Product::find($id)->toArray();
return view('cms.edit_product', self::$data);
}
public function update(ProductRequest $request, $id) {
Product::update_product($request, $id);
return redirect('cms/products');
}
public function destroy($id) {
Product::destroy($id);
Session::flash('sm', $request['title'] . ' has been deleted');
return redirect('cms/products');
}
@if($products)
<a href='{{url('shop/' . $url_category . '?order=high')}}' class='btn btn-link'>From High to Low</a>|
<a href='{{url('shop/' . $url_category . '?order=low')}}' class='btn btn-link' style='color:purple;'>From Low to High</a>
<div class="row">
@foreach($products as $row)
<div class="col-md-6 col-sm-6">
<h3>{{ $row['title'] }}</h3>
<p><a href="{{url('shop/'. $url_category . '/' . $row['url'])}}"><img alt="{{ $row['title'] }}" border="0" width="200" height="200" src="{{ asset('images/' . $row['image']) }}"></a></p>
<p>{!! $row['article'] !!}</p>
<p><strong>Price on site: </strong>{{ $row['price'] }}$</p>
<p>
<a href="{{url('shop/'. $url_category . '/' . $row['url'])}}" class="btn btn-warning">View Product Details</a>
<input @if( Cart::get($row['id'] )) disabled="disabled" @endif data-id="{{ $row['id'] }}" type="button" class="add-to-cart-btn btn btn-success" value="+ Add To Cart"/>
</p>
</div>
@endforeach
</div>
@else
<div class="row">
<div class="col-md-12">
<p><ans>No Products For This Category...</ans></p>
</div>
</div>
@endif
答案 0 :(得分:0)
您可能想要考虑不将$products
强制转换为数组,而是将其保留为集合。这样你就可以使用Laravel的sortBy()
方法以清晰的方式对集合进行排序。
// $order can be 'asc' or 'desc', which you determine in your controller
@foreach ($products->sortBy('column', $order) as $row)
请参阅此处的文档:Collections / sortBy()