|
4 | 4 |
|
5 | 5 | use App\Models\Category;
|
6 | 6 | use App\Models\Product;
|
| 7 | +use Illuminate\Database\Eloquent\Builder; |
7 | 8 | use Illuminate\Http\Request;
|
8 | 9 |
|
9 | 10 | class ProductController extends Controller
|
10 | 11 | {
|
11 | 12 | public function index()
|
12 | 13 | {
|
13 |
| - $products = Product::query() |
14 |
| - ->where('published', '=', 1) |
15 |
| - ->orderBy('updated_at', 'desc') |
16 |
| - ->paginate(5); |
17 |
| - return view('product.index', [ |
18 |
| - 'products' => $products |
19 |
| - ]); |
| 14 | + $query = Product::query(); |
| 15 | + |
| 16 | + return $this->renderProducts($query); |
20 | 17 | }
|
21 | 18 |
|
22 | 19 | public function byCategory(Category $category)
|
23 | 20 | {
|
24 | 21 | $categories = Category::getAllChildrenByParent($category);
|
25 | 22 |
|
26 |
| - $products = Product::query() |
| 23 | + $query = Product::query() |
27 | 24 | ->select('products.*')
|
28 | 25 | ->join('product_categories AS pc', 'pc.product_id', 'products.id')
|
| 26 | + ->whereIn('pc.category_id', array_map(fn($c) => $c->id, $categories)); |
| 27 | + |
| 28 | + return $this->renderProducts($query); |
| 29 | + } |
| 30 | + |
| 31 | + public function view(Product $product) |
| 32 | + { |
| 33 | + return view('product.view', ['product' => $product]); |
| 34 | + } |
| 35 | + |
| 36 | + private function renderProducts(Builder $query) |
| 37 | + { |
| 38 | + $search = \request()->get('search'); |
| 39 | + $products = $query |
29 | 40 | ->where('published', '=', 1)
|
30 |
| - ->whereIn('pc.category_id', array_map(fn($c) => $c->id, $categories)) |
| 41 | + ->where(function ($query) use ($search) { |
| 42 | + /** @var $query \Illuminate\Database\Eloquent\Builder */ |
| 43 | + $query->where('products.title', 'like', "%$search%") |
| 44 | + ->orWhere('products.description', 'like', "%$search%"); |
| 45 | + }) |
31 | 46 | ->orderBy('updated_at', 'desc')
|
32 | 47 | ->paginate(5);
|
33 | 48 |
|
34 | 49 | return view('product.index', [
|
35 | 50 | 'products' => $products
|
36 | 51 | ]);
|
37 |
| - } |
38 | 52 |
|
39 |
| - public function view(Product $product) |
40 |
| - { |
41 |
| - return view('product.view', ['product' => $product]); |
42 | 53 | }
|
43 | 54 | }
|
0 commit comments