From 2ce51785ebe13cb5ab56ddd0818f625954dd86e4 Mon Sep 17 00:00:00 2001 From: Zura Sekhniashvili Date: Sat, 21 Oct 2023 17:47:34 +0400 Subject: [PATCH] Implement sorting of products --- app/Http/Controllers/ProductController.php | 13 ++++- resources/views/product/index.blade.php | 64 +++++++++++++++++----- 2 files changed, 61 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index 22fe5c5..3ae8153 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -36,6 +36,17 @@ public function view(Product $product) private function renderProducts(Builder $query) { $search = \request()->get('search'); + $sort = \request()->get('sort', '-updated_at'); + + if ($sort) { + $sortDirection = 'asc'; + if ($sort[0] === '-') { + $sortDirection = 'desc'; + } + $sortField = preg_replace('/^-?/', '', $sort); + + $query->orderBy($sortField, $sortDirection); + } $products = $query ->where('published', '=', 1) ->where(function ($query) use ($search) { @@ -43,7 +54,7 @@ private function renderProducts(Builder $query) $query->where('products.title', 'like', "%$search%") ->orWhere('products.description', 'like', "%$search%"); }) - ->orderBy('updated_at', 'desc') + ->paginate(5); return view('product.index', [ diff --git a/resources/views/product/index.blade.php b/resources/views/product/index.blade.php index a8e8eb4..98dad2b 100644 --- a/resources/views/product/index.blade.php +++ b/resources/views/product/index.blade.php @@ -7,24 +7,58 @@ -
-
- +
+ + + + + + + + + + +
- count() === 0): ?> -
- There are no products published -
+ count() === 0 ): ?> +
+ There are no products published +
-
- @foreach($products as $product) - -
+ @foreach($products as $product) + +
@endforeach
- {{$products->links()}} + {{$products->appends(['sort' => request('sort'), 'search' => request('search')])->links()}}