fix: 🐛 update meilisearch to use one index for each model with multiple fields by locales
This commit is contained in:
parent
98e3103e47
commit
3dd626697e
22 changed files with 719 additions and 555 deletions
|
|
@ -1,78 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Document;
|
||||
use App\Models\DynamicPage;
|
||||
use App\Models\News;
|
||||
use App\Models\SearchIndex;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Str;
|
||||
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
|
||||
use Meilisearch\Client;
|
||||
|
||||
class MeilisearchUpdate extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'meilisearch:update';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Configure Meilisearch and rebuilt all indexes in all locales.';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
// Get new instance of Meilisearch client.
|
||||
$client = new Client(
|
||||
config('scout.meilisearch.host'),
|
||||
config('scout.meilisearch.key')
|
||||
);
|
||||
|
||||
// Get all supported locales defined in laravel localization config.
|
||||
$locales = LaravelLocalization::getSupportedLocales();
|
||||
|
||||
collect(array_keys($locales))->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}");
|
||||
});
|
||||
}
|
||||
}
|
||||
44
app/Console/Commands/UpdateMeilisearch.php
Normal file
44
app/Console/Commands/UpdateMeilisearch.php
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\DynamicPage;
|
||||
use App\Models\News;
|
||||
use App\Models\Document;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
|
||||
class UpdateMeilisearch extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'update-meilisearch';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Command description';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$models = [DynamicPage::class, News::class, Document::class];
|
||||
$locales = ['fr', 'en'];
|
||||
|
||||
foreach ($locales as $locale) {
|
||||
$this->info("Import {$locale}...");
|
||||
app()->setLocale($locale);
|
||||
|
||||
foreach ($models as $model) {
|
||||
$this->call('scout:import', ['model' => $model]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
|
||||
// Check if current word match exactly with terms.
|
||||
if (preg_match_all($pattern, $fullText, $matches, PREG_OFFSET_CAPTURE)) {
|
||||
foreach ($matches[0] as $match) {
|
||||
$matchPos = $match[1];
|
||||
$matchLen = strlen($match[0]);
|
||||
$ranges[] = [
|
||||
'start' => 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 = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
|
||||
$snippet = preg_replace(
|
||||
$pattern,
|
||||
'<span class="search-highlight">$0</span>',
|
||||
$snippet
|
||||
);
|
||||
}
|
||||
|
||||
$snippets[] = trim($snippet);
|
||||
if (count($snippets) >= 3) break;
|
||||
}
|
||||
|
||||
$result = implode('… ', $snippets);
|
||||
$result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result);
|
||||
|
||||
return trim($result);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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' => [
|
||||
|
|
|
|||
50
app/Http/Requests/Front/Search/SearchAjaxRequest.php
Normal file
50
app/Http/Requests/Front/Search/SearchAjaxRequest.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Front\Search;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
|
||||
|
||||
class SearchAjaxRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->ajax();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|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.");
|
||||
}
|
||||
},
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Front;
|
||||
namespace App\Http\Requests\Front\Search;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
|
|
@ -5,9 +5,9 @@ namespace App\Models;
|
|||
use App\Contracts\TranslatableModel;
|
||||
use App\Enums\Document\DocumentStatusEnum;
|
||||
use App\Enums\YearsEnum;
|
||||
use App\Helpers\DocumentHelper;
|
||||
use App\Helpers\TranslationHelper;
|
||||
use App\Traits\Models\HasCache;
|
||||
use App\Traits\Models\HasMeilisearchIndex;
|
||||
use App\Traits\Models\HasTranslations;
|
||||
use App\Traits\Models\HasUwilImages;
|
||||
use Carbon\Carbon;
|
||||
|
|
@ -16,7 +16,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Helpers\DocumentHelper;
|
||||
use Laravel\Scout\Searchable;
|
||||
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
|
||||
|
||||
class Document extends Model implements TranslatableModel
|
||||
|
|
@ -28,7 +28,7 @@ class Document extends Model implements TranslatableModel
|
|||
use HasUwilImages {
|
||||
HasUwilImages::inertiaFill as traitInertiaFill;
|
||||
}
|
||||
use HasMeilisearchIndex;
|
||||
use Searchable;
|
||||
|
||||
/**
|
||||
* Champs contenant des images dynamiques à gérer.
|
||||
|
|
@ -221,27 +221,81 @@ class Document extends Model implements TranslatableModel
|
|||
return sprintf('/%s', $targetModel->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<string, mixed>
|
||||
*/
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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<string, mixed>
|
||||
*/
|
||||
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
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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<string, mixed>
|
||||
*/
|
||||
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
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,152 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Laravel\Scout\Searchable;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SearchIndex extends Model
|
||||
{
|
||||
use Searchable;
|
||||
|
||||
/** @var string|null $table */
|
||||
protected $table = null;
|
||||
|
||||
/** @var boolean $timestamps */
|
||||
public $timestamps = false;
|
||||
|
||||
/** @var array $guarded */
|
||||
protected $guarded = [];
|
||||
|
||||
// * METHODS
|
||||
|
||||
/**
|
||||
* Unique name of the Meilisearch index.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function searchableAs(): string
|
||||
{
|
||||
return config('scout.prefix') . app()->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 = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
|
||||
// Check if current word match exactly with terms.
|
||||
if (preg_match_all($pattern, $fullText, $matches, PREG_OFFSET_CAPTURE)) {
|
||||
foreach ($matches[0] as $match) {
|
||||
$matchPos = $match[1];
|
||||
$matchLen = strlen($match[0]);
|
||||
$ranges[] = [
|
||||
'start' => 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 = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
|
||||
$snippet = preg_replace(
|
||||
$pattern,
|
||||
'<span class="search-highlight">$0</span>',
|
||||
$snippet
|
||||
);
|
||||
}
|
||||
|
||||
$snippets[] = trim($snippet);
|
||||
if (count($snippets) >= 3) break;
|
||||
}
|
||||
|
||||
$result = implode('… ', $snippets);
|
||||
$result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result);
|
||||
|
||||
return trim($result);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,113 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Traits\Models;
|
||||
|
||||
use App\Models\SearchIndex;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
|
||||
|
||||
/**
|
||||
* If there is a static function in a trait (named boot[TraitName]),
|
||||
* it will be executed as the boot() function would on an Eloquent model.
|
||||
* Futhermore, event in the Model observer doesn't erase actual events in the model,
|
||||
* but adds them.
|
||||
*/
|
||||
trait HasMeilisearchIndex
|
||||
{
|
||||
/**
|
||||
* Perform any actions required after the model boots.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function bootHasMeilisearchIndex(): void
|
||||
{
|
||||
$keyPrefix = Str::snake(class_basename(static::class));
|
||||
$usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive(static::class));
|
||||
|
||||
// Event executed avec saving a model.
|
||||
static::saved(function ($model) use ($keyPrefix, $usesSoftDeletes) {
|
||||
// Update ms index depending on status which is a global field non translatable.
|
||||
$statusChanged = $model->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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
<?php
|
||||
|
||||
use App\Models\Document;
|
||||
use App\Models\DynamicPage;
|
||||
use App\Models\News;
|
||||
|
||||
|
|
@ -87,7 +88,7 @@ return [
|
|||
|
|
||||
*/
|
||||
|
||||
'soft_delete' => 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,
|
||||
],
|
||||
],
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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 */
|
||||
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
@if ($models->lastPage() > 1)
|
||||
<div class="pgntn-page-pagination pgntn-bottom">
|
||||
<div class="pgntn-page-pagination-block">
|
||||
{{-- Page précédente --}}
|
||||
@if (!$models->onFirstPage())
|
||||
<a class="page-numbers prev" href="{{ $models->previousPageUrl() }}">
|
||||
{{ trans('front.search.previous')}}
|
||||
</a>
|
||||
@endif
|
||||
{{-- Pages --}}
|
||||
@for ($page = 1; $page <= $models->lastPage(); $page++)
|
||||
@if ($page == $models->currentPage())
|
||||
<span aria-current="page" class="page-numbers current">{{ $page }}</span>
|
||||
@else
|
||||
<a class="page-numbers" href="{{ $models->url($page) }}">
|
||||
{{ $page }}
|
||||
</a>
|
||||
@endif
|
||||
@endfor
|
||||
{{-- Page suivante --}}
|
||||
@if ($models->hasMorePages())
|
||||
<a class="page-numbers next" href="{{ $models->nextPageUrl() }}">
|
||||
{{ trans('front.search.next')}}
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
31
resources/views/components/front/search/card.blade.php
Normal file
31
resources/views/components/front/search/card.blade.php
Normal file
|
|
@ -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
|
||||
<a class="search-results__item" href="{{ $class::getAccessModel($result['id']) }}">
|
||||
@if($hasTitle)
|
||||
<div class="search-results__item-title">
|
||||
{!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["{$mainField}_{$currentLocale}"], $searchTerm) !!}
|
||||
</div>
|
||||
@endif
|
||||
<div @class([
|
||||
'no-bottom-margin-important no-bottom-padding-important' => !$hasDescription,
|
||||
'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true,
|
||||
])>
|
||||
@foreach($breadcrumbs as $breadcrumb)
|
||||
<span>{{ $breadcrumb->title }}</span>
|
||||
@if(!$loop->last)
|
||||
>
|
||||
@endif
|
||||
@endforeach
|
||||
@if($customBreadcrumbs && $hasTitle && end($breadcrumbs)->title !== $result["{$mainField}_{$currentLocale}"])
|
||||
<span>> {{ $result["{$mainField}_{$currentLocale}"] }}</span>
|
||||
@endif
|
||||
</div>
|
||||
@if ($hasDescription)
|
||||
<div class="search-results__item-text description">
|
||||
{!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["content_{$currentLocale}"], $searchTerm) !!}
|
||||
</div>
|
||||
@endif
|
||||
</a>
|
||||
90
resources/views/components/front/search/content.blade.php
Normal file
90
resources/views/components/front/search/content.blade.php
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
<div id="search-{{ $wrapperId }}" class="search-results">
|
||||
{{-- LOADER --}}
|
||||
<div id="search-loader-{{ $wrapperId }}" hidden>
|
||||
<div id="loader" class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
|
||||
</div>
|
||||
{{-- EMPTY RESULTS --}}
|
||||
<div id="search-empty-{{ $wrapperId }}" class="search-empty-results" hidden>
|
||||
{{ trans('front.search.no_results') }}
|
||||
</div>
|
||||
{{-- RESULTS --}}
|
||||
<div id="search-results-{{ $wrapperId }}"></div>
|
||||
{{-- PAGINATION --}}
|
||||
<div id="search-pagination-{{ $wrapperId }}"></div>
|
||||
</div>
|
||||
|
||||
@php
|
||||
// Set a template for the global count.
|
||||
$resultsLabel = trans('front.search.results_total', [
|
||||
'nbr' => '__COUNT__',
|
||||
'terms' => $searchTerm,
|
||||
]);
|
||||
$currentLocale = app()->getLocale();
|
||||
@endphp
|
||||
|
||||
@push('scripts')
|
||||
<script nonce="{{ $nonce }}">
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const wrapper = document.getElementById('search-{{ $wrapperId }}');
|
||||
if (!wrapper) return;
|
||||
|
||||
// Set a global count.
|
||||
window.searchTotal = window.searchTotal || 0;
|
||||
|
||||
const counter = document.querySelector('#search-global-count');
|
||||
const token = document.querySelector('meta[name="csrf-token"]').content;
|
||||
const results = wrapper.querySelector('#search-results-{{ $wrapperId }}');
|
||||
const pagination = wrapper.querySelector('#search-pagination-{{ $wrapperId }}');
|
||||
const empty = wrapper.querySelector('#search-empty-{{ $wrapperId }}');
|
||||
const loader = wrapper.querySelector('#search-loader-{{ $wrapperId }}');
|
||||
|
||||
loadPage(1);
|
||||
|
||||
// Call ajax to get results from a specific page.
|
||||
function loadPage(page) {
|
||||
loader.hidden = false;
|
||||
results.innerHTML = '';
|
||||
pagination.innerHTML = '';
|
||||
|
||||
fetch('/search/load/results', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': token,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
search: @json($searchTerm),
|
||||
page: Number(page),
|
||||
class: @json($class),
|
||||
locale: @json($currentLocale),
|
||||
})
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(update)
|
||||
.finally(() => {
|
||||
loader.hidden = true;
|
||||
});
|
||||
}
|
||||
|
||||
// Update content of results/pagination/count.
|
||||
function update(data) {
|
||||
results.innerHTML = data.items;
|
||||
pagination.innerHTML = data.pagination;
|
||||
empty.hidden = data.totalHits > 0;
|
||||
|
||||
window.searchTotal += Number(data.totalHits || 0);
|
||||
counter.innerHTML = @json($resultsLabel).replace('__COUNT__', window.searchTotal);
|
||||
|
||||
bindPagination();
|
||||
}
|
||||
|
||||
// Set events on new pagination.
|
||||
function bindPagination() {
|
||||
wrapper.querySelectorAll('[data-page]').forEach(btn => {
|
||||
btn.onclick = () => loadPage(btn.dataset.page);
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@endpush
|
||||
28
resources/views/components/front/search/pagination.blade.php
Normal file
28
resources/views/components/front/search/pagination.blade.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
@if ($models->lastPage() > 1)
|
||||
<div class="pgntn-page-pagination pgntn-bottom">
|
||||
<div class="pgntn-page-pagination-block">
|
||||
{{-- Previous button page --}}
|
||||
@if (!$models->onFirstPage())
|
||||
<button class="page-numbers prev" data-page="{{ $models->currentPage() - 1 }}">
|
||||
{{ trans('front.search.previous') }}
|
||||
</button>
|
||||
@endif
|
||||
{{-- Numbers pages --}}
|
||||
@for ($page = 1; $page <= $models->lastPage(); $page++)
|
||||
@if ($page == $models->currentPage())
|
||||
<span class="page-numbers current">{{ $page }}</span>
|
||||
@else
|
||||
<button class="page-numbers btn-page" data-page="{{ $page }}">
|
||||
{{ $page }}
|
||||
</button>
|
||||
@endif
|
||||
@endfor
|
||||
{{-- Next button page --}}
|
||||
@if ($models->hasMorePages())
|
||||
<button class="page-numbers next" data-page="{{ $models->currentPage() + 1 }}">
|
||||
{{ trans('front.search.next') }}
|
||||
</button>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
|
|
@ -14,7 +14,7 @@
|
|||
</form>
|
||||
</div>
|
||||
<div class="top-menu__item top-menu__item_lang langs">
|
||||
@foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
|
||||
@foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode)
|
||||
@if (!$loop->first)
|
||||
<span class="langs__separator"> / </span>
|
||||
@endif
|
||||
|
|
|
|||
|
|
@ -21,13 +21,11 @@
|
|||
@endif
|
||||
</ul>
|
||||
<div class="top-menu__item top-menu__item_lang langs">
|
||||
@foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
|
||||
@foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode)
|
||||
@if (!$loop->first)
|
||||
<span class="langs__separator"> / </span>
|
||||
@endif
|
||||
@php
|
||||
$url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode);
|
||||
@endphp
|
||||
@php $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); @endphp
|
||||
<a rel="alternate" hreflang="{{ $localeCode }}" href="{{ $url }}"
|
||||
class="langs__item {{ app()->getLocale() === $localeCode ? 'active' : '' }}">
|
||||
{{ strtoupper($localeCode) }}
|
||||
|
|
|
|||
|
|
@ -7,66 +7,32 @@
|
|||
<div class="search-page fw">
|
||||
@include('front.breadcrumbs.breadcrumb-body')
|
||||
<div class="search-page__wrapper wrapper">
|
||||
<h1 class="search-results-count subtitle">{{ trans('front.search.results_total', ['nbr' => $resultModels['totalHits'], 'terms' => $searchTerm]) }}</h1>
|
||||
<h1 id="search-global-count" class="search-results-count subtitle">
|
||||
{{ trans('front.search.results_total', [
|
||||
'nbr' => 0,
|
||||
'terms' => $searchTerm,
|
||||
]) }}
|
||||
</h1>
|
||||
<form class="form search-form" id="searchform" method="get" action="{{ route('front.search') }}">
|
||||
<div class="search-form__wrapper">
|
||||
<div class="search-form__field"><input class="search-form__input form__input" type="text" name="{{ trans('front.search.query') }}"
|
||||
placeholder="{{ trans('front.search.placeholder')}}" value="{{ $searchTerm }}"></div>
|
||||
<button class="search-form__btn" type="submit"><img class="search-form__btn-icon"
|
||||
src="/assets/img/search-icon_white.png" alt="{{ trans('front.search.trans')}}"></button>
|
||||
<div class="search-form__field">
|
||||
<input class="search-form__input form__input" type="text" name="{{ trans('front.search.query') }}"
|
||||
placeholder="{{ trans('front.search.placeholder')}}" value="{{ $searchTerm }}">
|
||||
</div>
|
||||
<button class="search-form__btn" type="submit">
|
||||
<img class="search-form__btn-icon" src="/assets/img/search-icon_white.png" alt="{{ trans('front.search.trans')}}">
|
||||
</button>
|
||||
</div>
|
||||
@error(trans('front.search.query'))
|
||||
<div class="form__error">{{ $message }}</div>
|
||||
@enderror
|
||||
</form>
|
||||
<div class="search-results">
|
||||
@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
|
||||
<a class="search-results__item" href="{{ $url }}">
|
||||
<div class="search-results__item-title">{!! \App\Models\SearchIndex::highlightTerms($result['title'], $searchTerm) !!}</div>
|
||||
<div @class([
|
||||
'no-bottom-margin-important no-bottom-padding-important' => !$hasDescription,
|
||||
'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true,
|
||||
])>
|
||||
@foreach(\Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray() as $breacrumb)
|
||||
<span>{{ $breacrumb->title }}</span>
|
||||
@if(!$loop->last)
|
||||
>
|
||||
@endif
|
||||
@endforeach
|
||||
@if($customBreadcrumbs)
|
||||
<span>> {{ $result['title'] }}</span>
|
||||
@endif
|
||||
</div>
|
||||
@if ($hasDescription)
|
||||
<div class="search-results__item-text description">
|
||||
<p>{!! \App\Models\SearchIndex::highlightTerms($result['content'], $searchTerm) !!}</p>
|
||||
</div>
|
||||
@endif
|
||||
</a>
|
||||
@empty
|
||||
<p>{{ trans('front.search.no_results')}}</p>
|
||||
@endforelse
|
||||
<x-front.search-pagination :models="$resultModels" />
|
||||
</div>
|
||||
<h3 class="subtitle">{{ str(trans_choice('models.classes.news', \INF))->ucFirst() }}</h3>
|
||||
<x-front.search.content :class="\App\Models\News::class" :searchTerm="$searchTerm" wrapperId="news" />
|
||||
<h3 class="subtitle">{{ str(trans_choice('models.classes.dynamic-page', \INF))->ucFirst() }}</h3>
|
||||
<x-front.search.content :class="\App\Models\DynamicPage::class" :searchTerm="$searchTerm" wrapperId="dynamicpages" />
|
||||
<h3 class="subtitle">{{ str(trans_choice('models.classes.document', \INF))->ucFirst() }}</h3>
|
||||
<x-front.search.content :class="\App\Models\Document::class" :searchTerm="$searchTerm" wrapperId="documents" />
|
||||
</div>
|
||||
</div>
|
||||
@endsection
|
||||
@endsection
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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 () {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue