diff --git a/app/Console/Commands/MeilisearchUpdate.php b/app/Console/Commands/MeilisearchUpdate.php deleted file mode 100644 index f98a8946..00000000 --- a/app/Console/Commands/MeilisearchUpdate.php +++ /dev/null @@ -1,78 +0,0 @@ -map(function (string $locale) use ($client) { - $localeName = Str::upper($locale); - $indexName = config('scout.prefix') . $locale; - $index = $client->index($indexName); - - $index->updateSearchableAttributes(['title', 'content']); - $index->updateFilterableAttributes(['type']); - - $this->info("Meilisearch indexes configured for locale: {$localeName}"); - - app()->setLocale($locale); - - SearchIndex::removeAllFromSearch(); - - collect([ - News::class, - DynamicPage::class, - Document::class, - ])->map(function(string $class) { - $class::chunk(100, function ($items) { - $items - ->map - ->toSearchDocument() - ->filter() - ->each - ->searchable(); - }); - }); - - $this->info("Meilisearch indexes rebuilt for locale: {$localeName}"); - }); - } -} diff --git a/app/Console/Commands/UpdateMeilisearch.php b/app/Console/Commands/UpdateMeilisearch.php new file mode 100644 index 00000000..ba7ec1c6 --- /dev/null +++ b/app/Console/Commands/UpdateMeilisearch.php @@ -0,0 +1,44 @@ +info("Import {$locale}..."); + app()->setLocale($locale); + + foreach ($models as $model) { + $this->call('scout:import', ['model' => $model]); + } + } + } +} diff --git a/app/Http/Controllers/Front/SearchController.php b/app/Http/Controllers/Front/SearchController.php index 981b03c0..8f2ad16f 100644 --- a/app/Http/Controllers/Front/SearchController.php +++ b/app/Http/Controllers/Front/SearchController.php @@ -2,43 +2,84 @@ namespace App\Http\Controllers\Front; -use App\Enums\StaticPageType; -use App\Http\Requests\Front\SearchRequest; -use App\Models\StaticPage; -use App\Models\SearchIndex; +use App\Http\Requests\Front\Search\SearchAjaxRequest; +use App\Http\Requests\Front\Search\SearchRequest; +use App\Models\Document; +use App\Models\DynamicPage; +use App\Models\News; +use App\Enums\Document\DocumentStatusEnum; +use App\Enums\News\NewsStatusEnum; +use App\Enums\DynamicPages\PageStatusEnum; use Illuminate\Http\Request; use Illuminate\Support\Str; +use Illuminate\Database\Eloquent\Builder; +use Mcamara\LaravelLocalization\LaravelLocalization; use Uwil\LaravelCommon\Controllers\Controller; use Uwil\LaravelCommon\Helpers\CollectionHelper; class SearchController extends Controller { /** - * Search page. + * Access to the search page. * - * @param \App\Http\Requests\Front\SearchRequest $request + * @param \App\Http\Requests\Front\Search\SearchRequest $request * @return \Illuminate\Contracts\View\View */ - public function search(SearchRequest $request): \Illuminate\Contracts\View\View + public function search(SearchRequest $request) { - $queryKey = trans('front.search.query'); - $pageKey = trans('front.search.page'); + $queryKey = trans('front.search.query'); $searchTerm = $request->validated()[$queryKey]; - $currentPage = $request->validated()[$pageKey]; - $perPage = 10; - - $searchQuery = $this->buildExactSearchQuery($searchTerm); - $resultModels = SearchIndex::search($searchQuery) - ->paginateRaw(perPage: $perPage, page: $currentPage); + return view('front.pages.search', compact('searchTerm')); + } + + /** + * Load results from search. + * + * @param \App\Http\Requests\Front\Search\SearchAjaxRequest $request + * @return \Illuminate\Http\JsonResponse + */ + public function ajaxSearchLoadResults(SearchAjaxRequest $request): \Illuminate\Http\JsonResponse + { + $class = $request->validated()['class']; + $searchTerm = $request->validated()['search']; + $currentPage = (int) $request->validated()['page']; + $currentLocale = $request->validated()['locale']; + $perPage = 5; - $resultModels->appends([ - $queryKey => $searchTerm, - $pageKey => $currentPage, - 'query' => null, + app()->setLocale($currentLocale); + $searchQuery = $this->buildExactSearchQuery($searchTerm); + + $models = $class::search($searchQuery, function ($engine, $query, $options) use ($class, $currentLocale) { + $options['attributesToSearchOn'] = $class::searchTransFields($currentLocale); + return $engine->search($query, $options); + }) + ->where('status', $class::searchStatusEnum()) + ->paginateRaw(perPage: $perPage, page: $currentPage); + + // Render items. + $itemsHtml = collect($models['hits'])->map(fn ($result) => + view('components.front.search.card', [ + 'class' => $class, + 'result' => $result, + 'mainField' => $class::searchMainField(), + 'routeName' => $class::searchRouteName($result['id_key'] ?? null), + 'customBreadcrumbs' => true, + 'searchTerm' => $searchTerm, + 'currentLocale' => $currentLocale, + ])->render() + )->implode(''); + + // Pagination. + $paginationHtml = view('components.front.search.pagination', [ + 'models' => $models, + ])->render(); + + return response()->json([ + 'items' => $itemsHtml, + 'pagination' => $paginationHtml, + 'totalHits' => $models['totalHits'], ]); - - return view('front.pages.search', compact('searchTerm', 'resultModels')); } /** @@ -60,4 +101,95 @@ class SearchController extends Controller return '+' . implode(' +', $exactTerms); } + + /** + * Highlights all search terms in a text. + * + * @param string $text + * @param string $searchTerm + * @return string + */ + public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string + { + if (trim($searchTerm) === '') { + return $text; + } + + // Clean terms list. + $words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY); + if (empty($words)) { + return $text; + } + + $fullText = strip_tags($text); + $textLength = strlen($fullText); + $ranges = []; + + // Collection of relevant ranges around each word. + foreach ($words as $word) { + $pattern = '/(? max(0, $matchPos - $contextLength), + 'end' => min($textLength, $matchPos + $matchLen + $contextLength), + ]; + } + } + } + + // Return the entire text if there isn't matches. + if (empty($ranges)) { + return $text; + } + + // Merging overlapping intervals. + usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']); + $merged = []; + foreach ($ranges as $r) { + if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) { + $merged[] = $r; + } else { + $merged[array_key_last($merged)]['end'] = max( + $merged[array_key_last($merged)]['end'], + $r['end'] + ); + } + } + + $snippets = []; + + foreach ($merged as $r) { + $snippet = substr($fullText, $r['start'], $r['end'] - $r['start']); + + // Cut cleanly without breaking the words + if ($r['start'] > 0) { + $snippet = preg_replace('/^\S*\s/', '…', $snippet, 1); + } + if ($r['end'] < $textLength) { + $snippet = preg_replace('/\s\S*$/', '…', $snippet, 1); + } + + // Highlighting searched words + foreach ($words as $word) { + $pattern = '/(?$0', + $snippet + ); + } + + $snippets[] = trim($snippet); + if (count($snippets) >= 3) break; + } + + $result = implode('… ', $snippets); + $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); + + return trim($result); + } } diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index c7d4454e..d1c7dbac 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -54,8 +54,6 @@ class HandleInertiaRequests extends Middleware ]), ]); - $locales = LaravelLocalization::getSupportedLocales(); - $props = [ ...parent::share($request), 'appEnv' => [ @@ -63,7 +61,7 @@ class HandleInertiaRequests extends Middleware 'name' => config('app.name'), 'url' => config('app.url'), 'locale' => app()->getLocale(), - 'locales' => array_keys($locales), + 'locales' => LaravelLocalization::getSupportedLanguagesKeys(), 'fallbackLocale' => app()->getFallbackLocale(), ], 'auth' => [ diff --git a/app/Http/Requests/Front/Search/SearchAjaxRequest.php b/app/Http/Requests/Front/Search/SearchAjaxRequest.php new file mode 100644 index 00000000..ac1e5029 --- /dev/null +++ b/app/Http/Requests/Front/Search/SearchAjaxRequest.php @@ -0,0 +1,50 @@ +ajax(); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + $supportedLocales = implode(',', LaravelLocalization::getSupportedLanguagesKeys()); + return [ + 'search' => 'required|string|between:3,255', + 'page' => 'required|integer|min:1', + 'locale' => "required|string|in:$supportedLocales", + 'class' => [ + 'required', + 'string', + 'starts_with:App\\Models\\', + // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed + function ($attribute, $value, $fail) { + if (!class_exists($value)) { + $fail("The specified model does not exist."); + return; + } + if (!is_subclass_of($value, Model::class)) { + $fail("The specified model is not an Eloquent model."); + } + }, + ], + ]; + } +} diff --git a/app/Http/Requests/Front/SearchRequest.php b/app/Http/Requests/Front/Search/SearchRequest.php similarity index 94% rename from app/Http/Requests/Front/SearchRequest.php rename to app/Http/Requests/Front/Search/SearchRequest.php index d6ee5b0b..f18e71f9 100644 --- a/app/Http/Requests/Front/SearchRequest.php +++ b/app/Http/Requests/Front/Search/SearchRequest.php @@ -1,6 +1,6 @@ path); } + // * MEILISEARCH + /** - * Set value of meilisearch indexes. + * Get model's setting to apply on scout search (meilisearch). * - * @return \App\Models\SearchIndex|null + * @var array */ - public function toSearchDocument(): ?\App\Models\SearchIndex + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchTransFields(string $currentLocale): array { - $locale = app()->getLocale(); + return [ + "name_$currentLocale", + "path_$currentLocale", + ]; + } - // Keep only published models. - if (!$this->status->equals(DocumentStatusEnum::published) || !$this->hasTranslation('path', $locale)) { - return null; + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return DocumentStatusEnum::published->value; + } + + /** + * Get front route. + * + * @return string + */ + public static function searchRouteName(): string + { + return 'front.documents.show'; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'name'; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'status' => $this->status->value, + ]; + foreach ($locales as $locale => $_) { + $data["name_$locale"] = $this->hasTranslation('name', $locale) ? $this->getTranslation('name', $locale) : null; + $data["path_$locale"] = $this->hasTranslation('path', $locale) ? $this->getTranslation('path', $locale) : null; } - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'slug' => $this->getTranslation('path', $locale), - 'title' => $this->getTranslation('name', $locale), - 'content' => null, - ]); + + return $data; } // * RELATIONSHIPS diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index ce6524e1..0e2bd95b 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -9,9 +9,7 @@ use App\Enums\DynamicPages\PageStatusEnum; use App\Helpers\DynamicPageHelper; use App\Helpers\RouteHelper; use App\Helpers\TranslationHelper; -use App\Models\SearchIndex; use App\Traits\Models\HasCache; -use App\Traits\Models\HasMeilisearchIndex; use App\Traits\Models\HasTranslations; use App\Traits\Models\HasUwilImages; use Illuminate\Database\Eloquent\Collection; @@ -22,6 +20,7 @@ use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; +use Laravel\Scout\Searchable; use Uwil\LaravelActivityLogs\Traits\ActivityLog; use Uwil\LaravelCommon\Helpers\FileHelper; @@ -47,7 +46,7 @@ class DynamicPage extends Model implements TranslatableModel use HasTranslations; use HasUwilImages; use SoftDeletes; - use HasMeilisearchIndex; + use Searchable; /** * The attributes that are mass assignable. @@ -319,44 +318,6 @@ class DynamicPage extends Model implements TranslatableModel return parse_url($url, PHP_URL_PATH) ?? "/"; } - /** - * Set value of meilisearch indexes. - * - * @return \App\Models\SearchIndex|null - */ - public function toSearchDocument(): ?\App\Models\SearchIndex - { - $locale = app()->getLocale(); - - // Keep only published models. - if (!$this->status->equals(PageStatusEnum::published) || !$this->hasTranslation('slug', $locale)) { - return null; - } - - // Clean content (no tags, no paths, no numbers, only string). - $content = strip_tags(collect($this->getTranslation('content', $locale)) - ->flatten() - ->filter(fn($value, $key) => - is_string($value) && - !empty($value) && - !is_numeric($value) && - !in_array($key, ['order', 'id']) && - !str_starts_with($key, 'image_') && - !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value) - ) - ->values() - ->implode(' ')); - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'id_key' => $this->id_key, - 'slug' => $this->getTranslation('slug', $locale), - 'title' => $this->getTranslation('title', $locale), - 'content' => $content - ]); - } - /** * Get localized path from the locale. * @@ -385,6 +346,117 @@ class DynamicPage extends Model implements TranslatableModel : $slug; } + // * MEILISEARCH + + /** + * Get model's setting to apply on scout search (meilisearch). + * + * @var array + */ + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @return array. + */ + public static function searchTransFields(): array + { + $currentLocale = app()->getLocale(); + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return PageStatusEnum::published->value; + } + + /** + * Get front route. + * + * @param string|null $idKey + * @return string + */ + public static function searchRouteName(string|null $idKey): string + { + $currentLocale = app()->getLocale(); + return "front.dynamic-pages.$idKey.$currentLocale"; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'title'; + } + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchableTransFields(string $currentLocale): array + { + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'id_key' => $this->id_key, + 'status' => $this->status->value, + ]; + + foreach ($locales as $locale => $_) { + $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; + + $content = $this->hasTranslation('content', $locale) ? strip_tags(collect($this->getTranslation('content', $locale)) + ->flatten() + ->filter(fn($value, $key) => + is_string($value) && + !empty($value) && + !is_numeric($value) && + !in_array($key, ['order', 'id']) && + !str_starts_with($key, 'image_') && + !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value) + ) + ->values() + ->implode(' ')) : null; + $data["content_$locale"] = $content; + } + + return $data; + } + // * RELATIONSHIPS /** diff --git a/app/Models/News.php b/app/Models/News.php index 3c9758a6..2f967f14 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -6,9 +6,7 @@ use App\Contracts\TranslatableModel; use App\Enums\News\NewsStatusEnum; use App\Helpers\TranslationHelper; use App\Models\NewsTag; -use App\Models\SearchIndex; use App\Traits\Models\HasCache; -use App\Traits\Models\HasMeilisearchIndex; use App\Traits\Models\HasTranslations; use App\Traits\Models\HasUwilImages; use Carbon\Carbon; @@ -19,6 +17,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Arr; use Illuminate\Support\Facades\App; use Illuminate\Support\Str; +use Laravel\Scout\Searchable; use Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable; use Uwil\LaravelActivityLogs\Traits\ActivityLog; @@ -50,7 +49,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable use HasUwilImages { HasUwilImages::inertiaFill as traitInertiaFill; } - use HasMeilisearchIndex; + use Searchable; /** * Get the route key for the model. @@ -295,9 +294,9 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable /** * Get data related to the first category of this news item. * - * @return NewsTag|null + * @return \App\Models\NewsTag|null */ - public function getFirstTagDataAttribute(): ?NewsTag + public function getFirstTagDataAttribute(): ?\App\Models\NewsTag { if (empty($this->tags) || empty($this->tags[0])) { return null; @@ -320,29 +319,6 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable TranslationHelper::validateFallbackTranslations($model); } - /** - * Set value of meilisearch indexes. - * - * @return \App\Models\SearchIndex|null - */ - public function toSearchDocument(): ?\App\Models\SearchIndex - { - $locale = app()->getLocale(); - - // Keep only published models. - if (!$this->status->equals(NewsStatusEnum::published) || !$this->hasTranslation('slug', $locale)) { - return null; - } - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'slug' => $this->getTranslation('slug', $locale), - 'title' => $this->getTranslation('title', $locale), - 'content' => strip_tags($this->getTranslation('content', $locale)), - ]); - } - /** * Get the url to access a specific resource. * @@ -358,6 +334,85 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable return route('front.news.show', $targetModel); } + // * MEILISEARCH + + /** + * Get model's setting to apply on scout search (meilisearch). + * + * @var array + */ + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchTransFields($currentLocale): array + { + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return NewsStatusEnum::published->value; + } + + /** + * Get front route. + * + * @return string + */ + public static function searchRouteName(): string + { + return 'front.news.show'; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'title'; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'status' => $this->status->value, + ]; + foreach ($locales as $locale => $_) { + $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; + $data["content_$locale"] = $this->hasTranslation('content', $locale) ? strip_tags($this->getTranslation('content', $locale)) : null; + } + + return $data; + } + // * RELATIONSHIPS /** diff --git a/app/Models/SearchIndex.php b/app/Models/SearchIndex.php deleted file mode 100644 index 2027a14e..00000000 --- a/app/Models/SearchIndex.php +++ /dev/null @@ -1,152 +0,0 @@ -getLocale(); - } - - /** - * Unique primary key. - * - * @return string - */ - public function getScoutKey(): mixed - { - return "{$this->type}_{$this->model_id}"; - } - - /** - * Indexed data. - * - * @return array - */ - public function toSearchableArray(): array - { - return [ - 'id' => $this->getScoutKey(), - 'type' => $this->type, - 'model_id' => $this->model_id, - 'id_key' => $this->id_key ?? null, - 'slug' => $this->slug, - 'title' => $this->title, - 'content' => $this->content, - ]; - } - - /** - * Highlights all search terms in a text. - * - * @param string $text - * @param string $searchTerm - * @return string - */ - public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string - { - if (trim($searchTerm) === '') { - return $text; - } - - // Clean terms list. - $words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY); - if (empty($words)) { - return $text; - } - - $fullText = strip_tags($text); - $textLength = strlen($fullText); - $ranges = []; - - // Collection of relevant ranges around each word. - foreach ($words as $word) { - $pattern = '/(? max(0, $matchPos - $contextLength), - 'end' => min($textLength, $matchPos + $matchLen + $contextLength), - ]; - } - } - } - - // Return the entire text if there isn't matches. - if (empty($ranges)) { - return $text; - } - - // Merging overlapping intervals. - usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']); - $merged = []; - foreach ($ranges as $r) { - if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) { - $merged[] = $r; - } else { - $merged[array_key_last($merged)]['end'] = max( - $merged[array_key_last($merged)]['end'], - $r['end'] - ); - } - } - - $snippets = []; - - foreach ($merged as $r) { - $snippet = substr($fullText, $r['start'], $r['end'] - $r['start']); - - // Cut cleanly without breaking the words - if ($r['start'] > 0) { - $snippet = preg_replace('/^\S*\s/', '…', $snippet, 1); - } - if ($r['end'] < $textLength) { - $snippet = preg_replace('/\s\S*$/', '…', $snippet, 1); - } - - // Highlighting searched words - foreach ($words as $word) { - $pattern = '/(?$0', - $snippet - ); - } - - $snippets[] = trim($snippet); - if (count($snippets) >= 3) break; - } - - $result = implode('… ', $snippets); - $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); - - return trim($result); - } -} diff --git a/app/Traits/Models/HasMeilisearchIndex.php b/app/Traits/Models/HasMeilisearchIndex.php deleted file mode 100644 index 5384c165..00000000 --- a/app/Traits/Models/HasMeilisearchIndex.php +++ /dev/null @@ -1,113 +0,0 @@ -wasChanged('status'); - $originalLocale = app()->getLocale(); - $locales = $statusChanged - ? array_keys(LaravelLocalization::getSupportedLocales()) - : [$originalLocale]; - - // Loop on all locales to update indexes when global fields like status is updated, - // Otherwise, on current locale. - collect($locales)->map(function($locale) use ($keyPrefix, $model, $usesSoftDeletes) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - $indexId = "{$keyPrefix}_{$model->getKey()}"; - - // Remove model from meilisearch index. - if ($usesSoftDeletes && method_exists($model, 'trashed') && $model->trashed()) { - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - return; - } - $msIndex = $model->toSearchDocument(); - // Add model to the meilisearch index if conditions are true, remove from it if not. - if ($msIndex) { - $msIndex->searchable(); - } else { - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - } - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - - static::deleted(function ($model) use ($keyPrefix) { - $originalLocale = app()->getLocale(); - $locales = array_keys(LaravelLocalization::getSupportedLocales()); - - // Loop on all locales to update indexes when model is deleted (softdeleted or not). - collect($locales)->map(function($locale) use ($keyPrefix, $model) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - $indexId = "{$keyPrefix}_{$model->getKey()}"; - // Remove model from meilisearch index. - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - - if ($usesSoftDeletes) { - static::restored(function ($model) { - $originalLocale = app()->getLocale(); - $locales = array_keys(LaravelLocalization::getSupportedLocales()); - - // Loop on all locales to update indexes when model is restored. - collect($locales)->map(function($locale) use ($model) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - // Add model to the meilisearch index if conditions are true. - $msIndex = $model->toSearchDocument(); - if ($msIndex) { - $msIndex->searchable(); - } - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - } - } -} diff --git a/config/scout.php b/config/scout.php index 794a607e..d05b4e71 100644 --- a/config/scout.php +++ b/config/scout.php @@ -1,5 +1,6 @@ true, + 'soft_delete' => false, /* |-------------------------------------------------------------------------- @@ -105,6 +106,10 @@ return [ 'meilisearch' => [ 'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'), 'key' => env('MEILISEARCH_KEY'), - 'index-settings' => [], + 'index-settings' => [ + DynamicPage::class => DynamicPage::$searchSettings, + Document::class => Document::$searchSettings, + News::class => News::$searchSettings, + ], ], ]; diff --git a/public/assets/css/style.css b/public/assets/css/style.css index 83119b1e..9747d058 100644 --- a/public/assets/css/style.css +++ b/public/assets/css/style.css @@ -3300,6 +3300,15 @@ div.search-results { font-weight: 700; } +.search-empty-results { + height: 80px; + padding: 30px 0; +} + +.search-page .page-numbers { + cursor: pointer; +} + /* page search END */ /* pagination START */ diff --git a/resources/views/components/front/search-pagination.blade.php b/resources/views/components/front/search-pagination.blade.php deleted file mode 100644 index 629294a0..00000000 --- a/resources/views/components/front/search-pagination.blade.php +++ /dev/null @@ -1,28 +0,0 @@ -@if ($models->lastPage() > 1) -
-
- {{-- Page précédente --}} - @if (!$models->onFirstPage()) - - @endif - {{-- Pages --}} - @for ($page = 1; $page <= $models->lastPage(); $page++) - @if ($page == $models->currentPage()) - {{ $page }} - @else - - {{ $page }} - - @endif - @endfor - {{-- Page suivante --}} - @if ($models->hasMorePages()) - - @endif -
-
-@endif \ No newline at end of file diff --git a/resources/views/components/front/search/card.blade.php b/resources/views/components/front/search/card.blade.php new file mode 100644 index 00000000..3773f122 --- /dev/null +++ b/resources/views/components/front/search/card.blade.php @@ -0,0 +1,31 @@ +@php + $hasTitle = isset($result["{$mainField}_{$currentLocale}"]) && !is_null($result["{$mainField}_{$currentLocale}"]) && !empty($result["{$mainField}_{$currentLocale}"]); + $hasDescription = isset($result["content_{$currentLocale}"]) && !is_null($result["content_{$currentLocale}"]) && !empty($result["content_{$currentLocale}"]); + $breadcrumbs = \Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray(); +@endphp + + @if($hasTitle) +
+ {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["{$mainField}_{$currentLocale}"], $searchTerm) !!} +
+ @endif +
!$hasDescription, + 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, + ])> + @foreach($breadcrumbs as $breadcrumb) + {{ $breadcrumb->title }} + @if(!$loop->last) + > + @endif + @endforeach + @if($customBreadcrumbs && $hasTitle && end($breadcrumbs)->title !== $result["{$mainField}_{$currentLocale}"]) + > {{ $result["{$mainField}_{$currentLocale}"] }} + @endif +
+ @if ($hasDescription) +
+ {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["content_{$currentLocale}"], $searchTerm) !!} +
+ @endif +
\ No newline at end of file diff --git a/resources/views/components/front/search/content.blade.php b/resources/views/components/front/search/content.blade.php new file mode 100644 index 00000000..f249b244 --- /dev/null +++ b/resources/views/components/front/search/content.blade.php @@ -0,0 +1,90 @@ +
+ {{-- LOADER --}} + + {{-- EMPTY RESULTS --}} + + {{-- RESULTS --}} +
+ {{-- PAGINATION --}} +
+
+ +@php + // Set a template for the global count. + $resultsLabel = trans('front.search.results_total', [ + 'nbr' => '__COUNT__', + 'terms' => $searchTerm, + ]); + $currentLocale = app()->getLocale(); +@endphp + +@push('scripts') + +@endpush \ No newline at end of file diff --git a/resources/views/components/front/search/pagination.blade.php b/resources/views/components/front/search/pagination.blade.php new file mode 100644 index 00000000..3a8f32ff --- /dev/null +++ b/resources/views/components/front/search/pagination.blade.php @@ -0,0 +1,28 @@ +@if ($models->lastPage() > 1) +
+
+ {{-- Previous button page --}} + @if (!$models->onFirstPage()) + + @endif + {{-- Numbers pages --}} + @for ($page = 1; $page <= $models->lastPage(); $page++) + @if ($page == $models->currentPage()) + {{ $page }} + @else + + @endif + @endfor + {{-- Next button page --}} + @if ($models->hasMorePages()) + + @endif +
+
+@endif diff --git a/resources/views/front/layouts/mobile-menu.blade.php b/resources/views/front/layouts/mobile-menu.blade.php index 03ebd978..00de9366 100644 --- a/resources/views/front/layouts/mobile-menu.blade.php +++ b/resources/views/front/layouts/mobile-menu.blade.php @@ -14,7 +14,7 @@
- @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties) + @foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode) @if (!$loop->first) / @endif diff --git a/resources/views/front/layouts/top-nav-menu.blade.php b/resources/views/front/layouts/top-nav-menu.blade.php index 2e7887b9..31772675 100644 --- a/resources/views/front/layouts/top-nav-menu.blade.php +++ b/resources/views/front/layouts/top-nav-menu.blade.php @@ -21,13 +21,11 @@ @endif
- @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties) + @foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode) @if (!$loop->first) / @endif - @php - $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); - @endphp + @php $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); @endphp {{ strtoupper($localeCode) }} diff --git a/resources/views/front/pages/search.blade.php b/resources/views/front/pages/search.blade.php index 61bde2e2..27deb3c6 100644 --- a/resources/views/front/pages/search.blade.php +++ b/resources/views/front/pages/search.blade.php @@ -7,66 +7,32 @@
@include('front.breadcrumbs.breadcrumb-body')
-

{{ trans('front.search.results_total', ['nbr' => $resultModels['totalHits'], 'terms' => $searchTerm]) }}

+

+ {{ trans('front.search.results_total', [ + 'nbr' => 0, + 'terms' => $searchTerm, + ]) }} +

-
- +
+ +
+
@error(trans('front.search.query'))
{{ $message }}
@enderror
-
- @forelse($resultModels['hits'] as $result) - @php - $locale = app()->getLocale(); - $hasDescription = isset($result['content']) && !is_null($result['content']) && !empty($result['content']); - @endphp - @php - if ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\DynamicPage::class))) { - $url = \App\Models\DynamicPage::getAccessModel($result['model_id']); - $routeName = sprintf('front.dynamic-pages.%s.%s', $result['id_key'], $locale); - $customBreadcrumbs = false; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\News::class))) { - $url = \App\Models\News::getAccessModel($result['model_id']); - $routeName = 'front.news.show'; - $customBreadcrumbs = true; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\Document::class))) { - $url = \App\Models\Document::getAccessModel($result['model_id']); - $routeName = 'front.documents.show'; - $customBreadcrumbs = true; - } - @endphp - -
{!! \App\Models\SearchIndex::highlightTerms($result['title'], $searchTerm) !!}
-
!$hasDescription, - 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, - ])> - @foreach(\Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray() as $breacrumb) - {{ $breacrumb->title }} - @if(!$loop->last) - > - @endif - @endforeach - @if($customBreadcrumbs) - > {{ $result['title'] }} - @endif -
- @if ($hasDescription) -
-

{!! \App\Models\SearchIndex::highlightTerms($result['content'], $searchTerm) !!}

-
- @endif -
- @empty -

{{ trans('front.search.no_results')}}

- @endforelse - -
+

{{ str(trans_choice('models.classes.news', \INF))->ucFirst() }}

+ +

{{ str(trans_choice('models.classes.dynamic-page', \INF))->ucFirst() }}

+ +

{{ str(trans_choice('models.classes.document', \INF))->ucFirst() }}

+
-@endsection +@endsection \ No newline at end of file diff --git a/routes/breadcrumbs-front.php b/routes/breadcrumbs-front.php index 64dd2303..3ec67921 100644 --- a/routes/breadcrumbs-front.php +++ b/routes/breadcrumbs-front.php @@ -18,18 +18,20 @@ $pageHome = DynamicPage::getModelsCached() ->first(); // * DYNAMIC PAGES. -DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($currentLocale, $pageHome) { - Breadcrumbs::for( - sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $currentLocale), - function (Generator $trail) use ($currentLocale, $dynamicPageModel, $pageHome) { - if (!is_null($dynamicPageModel->page_id)) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $currentLocale)); - } elseif (isset($pageHome) && $dynamicPageModel->id_key !== $pageHome->id_key) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $currentLocale)); +DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($supportedLocales, $pageHome) { + collect($supportedLocales)->map(function (string $locale) use ($dynamicPageModel, $pageHome) { + Breadcrumbs::for( + sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $locale), + function (Generator $trail) use ($locale, $dynamicPageModel, $pageHome) { + if (!is_null($dynamicPageModel->page_id)) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $locale)); + } elseif (isset($pageHome) && $dynamicPageModel->id_key !== $pageHome->id_key) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $locale)); + } + $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); } - $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); - } - ); + ); + }); }); // * CONTACT INDEX. diff --git a/routes/web-front.php b/routes/web-front.php index c805e74d..20a29f3a 100644 --- a/routes/web-front.php +++ b/routes/web-front.php @@ -28,6 +28,7 @@ Route::group( // Search routes. Route::get(LaravelLocalization::transRoute('routes.search'), [SearchController::class, 'search'])->name('search'); + Route::post('/search/load/results', [SearchController::class, 'ajaxSearchLoadResults'])->name('search.ajax.news'); // Filters routes. Route::prefix('posts')->group(function () {