2026-09-03 16:28:10 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
2026-10-19 17:32:35 +03:00
|
|
|
use App\Catalog\ProductCard;
|
2026-09-04 13:07:57 +03:00
|
|
|
use App\Catalog\ProductListing;
|
|
|
|
|
use App\Catalog\ProductListingPage;
|
2026-10-19 17:32:35 +03:00
|
|
|
use Modules\Core\Catalog\Services\ProductSearchService;
|
2026-09-03 16:28:10 +03:00
|
|
|
|
|
|
|
|
class SearchController extends Controller
|
|
|
|
|
{
|
2026-10-19 17:32:35 +03:00
|
|
|
/** Live search answers from this many characters on. */
|
|
|
|
|
public const LIVE_MIN_CHARS = 3;
|
|
|
|
|
|
|
|
|
|
/** How many products the live search dropdown lists. */
|
|
|
|
|
private const LIVE_LIMIT = 6;
|
|
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
|
private readonly ProductListingPage $listingPage,
|
|
|
|
|
private readonly ProductSearchService $search,
|
|
|
|
|
) {}
|
2026-09-03 16:28:10 +03:00
|
|
|
|
|
|
|
|
public function show(string $locale)
|
|
|
|
|
{
|
|
|
|
|
$query = trim((string) request()->query('q', ''));
|
|
|
|
|
|
2026-10-19 17:32:35 +03:00
|
|
|
// The search overlay's live results: the same endpoint, asked for by
|
|
|
|
|
// its <turbo-frame id="search-suggestions"> as the shopper types.
|
|
|
|
|
if (request()->header('Turbo-Frame') === 'search-suggestions') {
|
|
|
|
|
return $this->suggestions($query);
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-03 16:28:10 +03:00
|
|
|
if ($query === '') {
|
|
|
|
|
return redirect()->route('products');
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-04 13:07:57 +03:00
|
|
|
$listing = ProductListing::fromRequest(request());
|
2026-09-03 16:28:10 +03:00
|
|
|
|
2026-09-04 13:07:57 +03:00
|
|
|
$data = $this->listingPage->build(
|
|
|
|
|
$listing,
|
|
|
|
|
fn (array $overrides) => route('search', ['q' => $query] + $overrides),
|
|
|
|
|
collectionId: null,
|
|
|
|
|
query: $query,
|
2026-09-03 16:28:10 +03:00
|
|
|
);
|
|
|
|
|
|
2026-09-04 13:07:57 +03:00
|
|
|
return view('search.index', [...$data, 'query' => $query]);
|
2026-09-03 16:28:10 +03:00
|
|
|
}
|
2026-10-19 17:32:35 +03:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The first few matches and how many there are in all — the dropdown
|
|
|
|
|
* under the search overlay. Empty below LIVE_MIN_CHARS characters.
|
|
|
|
|
*/
|
|
|
|
|
private function suggestions(string $query)
|
|
|
|
|
{
|
|
|
|
|
$products = collect();
|
|
|
|
|
$total = 0;
|
|
|
|
|
|
|
|
|
|
if (mb_strlen($query) >= self::LIVE_MIN_CHARS) {
|
|
|
|
|
$result = $this->search->search($query, perPage: self::LIVE_LIMIT);
|
|
|
|
|
$products = collect($result->products->items())->map(ProductCard::fromIndexed(...));
|
|
|
|
|
$total = $result->products->total();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return view('search.suggestions', [
|
|
|
|
|
'query' => $query,
|
|
|
|
|
'products' => $products,
|
|
|
|
|
'total' => $total,
|
|
|
|
|
'searched' => mb_strlen($query) >= self::LIVE_MIN_CHARS,
|
|
|
|
|
]);
|
|
|
|
|
}
|
2026-09-04 13:19:24 +03:00
|
|
|
}
|