dijkr / Copia

Laravel-project with CMS
0 stars 0 forks source link

Need a search function to search for products #25

Closed dijkr closed 1 year ago

dijkr commented 1 year ago

To start of, just a simple search should display the products at the producten-view. Since the results could provide products from multiple categories. It should get a specific banner, but a generic banner to display above the results.

dijkr commented 1 year ago

This works for a simple search: Product::where('Title', 'LIKE', '%' . $keyword . '%')->get(); This should be put in a function and the function should be called when hitting the search button. It off course should use the keyword to query the database.

dijkr commented 1 year ago

This is the first build to start wtih.

Route: Route::post('search', [ProductController::class, 'searchProduct']);

Controller:

    public function searchProduct($keyword)
    {
        // Database query
        $search = Product::where('Title', 'LIKE', '%' . $keyword . '%')->get();

        return View::make('producten')
            ->layout('layout')
            ->with(['search' => $search
            ]);
    }
dijkr commented 1 year ago

Now, the controller uses the same function as for groupedProdutcs. But now it takes the result of the search(form)field from the request. Then it uses the keyword to query the database. Another view is used, because the producten-view uses a category banner, and searchresults can display products from different categories.

Route: Route::post('search', [ProductController::class, 'searchProduct']);

Controller:

    public function searchProduct(Request $request)
    {
        // Database query
        $keyword = $request->input('keyword');
        $products = Product::where('Title', 'LIKE', '%' . $keyword . '%')->get();

        $searchResults = $products->groupBy('Subcategory')->mapWithKeys(function ($products, $key) {
            $subcategory = json_decode($key, true);
            $name = $subcategory['name'];
            return [$name => $products];
        });

        return View::make('searchresults')
            ->layout('layout')
            ->with(['searchResults' => $searchResults
            ]);
    }

View:

    <div class="search-pt">
         <form method="POST" class="type-1" action="search">
             {{ csrf_field }}
            {{# SEARCHFIELD #}}
             <div class="searchfield"><input type="text" name="keyword" placeholder="Zoeken.."></div>
             {{# SEARCH ICON #}}
            <div class="searchicon">
                <button type="submit" style="background: none; border: none;">
                    <a href><i class="fa-solid fa-magnifying-glass fa-rotate-90" style="color: #ffffff;"></i></a>
                </button>
            </div>
        </form>
    </div>