refactor: ♻️ improve articles and documents fetching using HasCache trait

This commit is contained in:
Corentin Huet 2026-01-09 17:07:50 +01:00
parent d3fe0076d8
commit ece720a5d9
8 changed files with 203 additions and 184 deletions

View file

@ -1,75 +0,0 @@
<?php
namespace App\Helpers;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Builder;
class CollectionHelper
{
/**
* Extract unique enum values from a model field.
*
* @param string $model
* @param string $field
*
* @return \Illuminate\Support\Collection
*/
function getUniqueEnumValues(string $model, string $field): Collection
{
return $model::pluck($field)
->map(fn($enum) => $enum->value)
->unique()
->values();
}
/**
* Extract unique years from date field in a query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $field
*
* @return \Illuminate\Support\Collection
*/
function getUniqueEnumValuesFromQuery(Builder $query, string $field): Collection
{
return $query->pluck($field)
->map(fn($enum) => $enum->value ?? '')
->unique()
->values();
}
/**
* Extract unique years from date field in a query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $field
*
* @return \Illuminate\Support\Collection
*/
function getUniqueYearsFromQuery(Builder $query, string $field): Collection
{
return $query->pluck($field)
->map(fn($date) => Carbon::parse($date)->year)
->unique()
->values();
}
/**
* Filter input collection to only keep items whose value exists in a reference collection.
*
* @param \Illuminate\Support\Collection $array1
* @param \Illuminate\Support\Collection $array2
* @param string|null $field
*
* @return array
*/
function getMatchingValues(Collection $array1, Collection $array2, ?string $field = null): array
{
return $array2
->filter(fn ($item) => $array1->contains($field ? $item[$field] : $item))
->values()
->toArray();
}
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Front;
use Carbon\Carbon;
use App\Models\News;
use App\Models\NewsTag;
use App\Enums\YearsEnum;
@ -9,19 +10,46 @@ use App\Models\Document;
use App\Enums\OrdersEnum;
use App\Models\DocumentTag;
use Illuminate\Support\Str;
use App\Helpers\CollectionHelper;
use App\Enums\News\NewsStatusEnum;
use Illuminate\Support\Facades\App;
use App\Helpers\BladeComponentHelper;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use App\Http\Requests\Front\PostsRequest;
use Illuminate\Database\Eloquent\Builder;
use App\Enums\Document\DocumentStatusEnum;
use Illuminate\Database\Eloquent\Collection;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Helpers\CollectionHelper;
class PostsController extends Controller
{
/**
* Extract unique years from date field in a collection.
*
* @param \Illuminate\Support\Collection $query
* @param string $field
*
* @return \Illuminate\Support\Collection
*/
private function getUniqueYearsFromCollection(Collection $model, string $field): Collection
{
return $model->pluck($field)
->map(fn($date) => Carbon::parse($date)->year)
->unique()
->values();
}
/**
* Filter input collection to only keep items whose value exists in a reference collection.
*
* @param \Illuminate\Support\Collection $array1
* @param \Illuminate\Support\Collection $array2
* @param string|null $field
*
* @return array
*/
function getMatchingValues(Collection $array1, Collection $array2, ?string $field = null): array
{
return $array2
->filter(fn ($item) => $array1->contains($field ? $item[$field] : $item))
->values()
->toArray();
}
/**
* Build the common filters configuration for front-end listing pages
*
@ -30,14 +58,13 @@ class PostsController extends Controller
* @param string $type
* @param string $category
* @param \Illuminate\Database\Eloquent\Collection $publishedTags
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Collection $model
*
* @return array
*/
private function getFilters(string $type, string $category, Collection $publishedTags, Builder $query): array
private function getFilters(string $type, string $category, Collection $publishedTags, Collection $model): array
{
$filters = [];
$collectionHelper = new CollectionHelper();
$tags = collect($publishedTags)
->map(fn($tag) => [
@ -70,8 +97,8 @@ class PostsController extends Controller
->values();
/** Sort displayed years */
$years = $collectionHelper->getMatchingValues(
$collectionHelper->getUniqueYearsFromQuery($query, 'published_at'),
$years = $this->getMatchingValues(
$this->getUniqueYearsFromCollection($model, 'published_at'),
$enumYears,
'value'
);
@ -119,8 +146,7 @@ class PostsController extends Controller
$publishedNewsTags = NewsTag::getTagsByCategoryInCurrentLocale($category);
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */
$query = News::getPublishedNewsByCategoryInCurrentLocale($category);
$newsModel = News::getPublishedNewsByCategoryInCurrentLocale($category);
$requestedTags = collect($data['filters']['tags'] ?? '')
->filter()
@ -138,8 +164,10 @@ class PostsController extends Controller
->values();
if ($selectedTags->isNotEmpty()) {
$query->whereHas('tags', function ($q) use ($selectedTags) {
$q->whereIn('newsable_id', $selectedTags->map->id->all());
$newsModel = $newsModel->filter(function ($news) use ($selectedTags) {
return $news->tags->contains(
fn ($tag) => $selectedTags->contains('id', $tag->id)
);
});
$selectedFilters['tags'] = $selectedTags;
@ -157,20 +185,19 @@ class PostsController extends Controller
->values();
if ($selectedYears->isNotEmpty()) {
foreach ($selectedYears->map->value->all() as $value) {
$query->whereYear('published_at', $value);
}
$newsModel = $newsModel->filter(function ($news) use ($selectedYears) {
return $selectedYears->contains('value', $news->published_at->year);
});
$selectedFilters['years'] = $selectedYears;
}
/** Sort columns with a query */
$this->sortQuery($query);
$newsModel = $newsModel->sortByDesc('published_at');
$filters = $this->getFilters('news', $category, $publishedNewsTags, $query);
$filters = $this->getFilters('news', $category, $publishedNewsTags, $newsModel);
/** Custom pagination */
$newsModel = $query->paginate($perPage, ['*'], 'page', $data['page'] ?? 1);
$newsModel = CollectionHelper::paginate($newsModel, $perPage);
return response()->json([
'pagination' => [
@ -205,8 +232,7 @@ class PostsController extends Controller
$publishedDocumentsTags = DocumentTag::getTagsByCategoryInCurrentLocale($category);
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query */
$query = Document::getPublishedDocumentsByCategoryInCurrentLocale($category);
$documentsModel = Document::getPublishedDocumentsByCategoryInCurrentLocale($category);
$requestedTags = collect($data['filters']['tags'] ?? '')
->filter()
@ -224,8 +250,10 @@ class PostsController extends Controller
->values();
if ($selectedTags->isNotEmpty()) {
$query->whereHas('tags', function ($q) use ($selectedTags) {
$q->whereIn('documentable_id', $selectedTags->map->id->all());
$documentsModel = $documentsModel->filter(function ($documents) use ($selectedTags) {
return $documents->tags->contains(
fn ($tag) => $selectedTags->contains('id', $tag->id)
);
});
$selectedFilters['tags'] = $selectedTags;
@ -243,9 +271,9 @@ class PostsController extends Controller
->values();
if ($selectedYears->isNotEmpty()) {
foreach ($selectedYears->map->value->all() as $value) {
$query->where('exercice', $value);
}
$documentsModel = $documentsModel->filter(function ($documents) use ($selectedYears) {
return $selectedYears->contains('value', $documents->exercice);
});
$selectedFilters['years'] = $selectedYears;
}
@ -261,18 +289,19 @@ class PostsController extends Controller
->values();
if ($selectedOrder->isNotEmpty()) {
$query->orderBy('published_at', $selectedOrder->map->tag->first());
$documentsModel = $selectedOrder->map->tag->first() === 'desc'
? $documentsModel->sortByDesc('published_at')
: $documentsModel->sortBy('published_at');
$selectedFilters['order'] = $selectedOrder->all();
} else {
$documentsModel = $documentsModel->sortByDesc('published_at');
}
/** Sort columns with a query */
$this->sortQuery($query);
$filters = $this->getFilters('documents', $category, $publishedDocumentsTags, $query);
$filters = $this->getFilters('documents', $category, $publishedDocumentsTags, $documentsModel);
/** Custom pagination */
$documentsModel = $query->paginate($perPage, ['*'], 'page', $data['page'] ?? 1);
$documentsModel = CollectionHelper::paginate($documentsModel, $perPage);
return response()->json([
'pagination' => [

View file

@ -71,6 +71,16 @@ class Document extends Model implements TranslatableModel
'path',
];
/**
* Relations should be included in the cache.
*
* @var array<string, string>
*/
protected static $cacheRelations = [
'categories',
'tags',
];
/**
* Perform any actions required after the model boots.
*
@ -242,15 +252,23 @@ class Document extends Model implements TranslatableModel
$this->traitInertiaFill($attributes);
}
public static function getPublishedDocumentsByCategoryInCurrentLocale($category)
/**
* Get all published news by category.
*
* @param string $category
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getPublishedDocumentsByCategoryInCurrentLocale(string $category)
{
$locale = App::getLocale();
// ici mettre le cache avec la relation catégorie
return Document::query()
->with('categories', 'tags')
->whereNotNull("path->$locale")
->whereHas('categories', function ($q) use ($locale, $category) {
$q->where("slug->$locale", $category);
return Document::getModelsCached()
->where('status', DocumentStatusEnum::published)
->filter(function ($documents) use ($category, $locale) {
return !empty($documents->getTranslation('path', $locale, false)) && $documents->categories->contains(
fn ($cat) => $cat->slug === $category
);
});
}
}

View file

@ -39,6 +39,15 @@ class DocumentTag extends Model implements TranslatableModel
'slug'
];
/**
* Relations should be included in the cache.
*
* @var array<string, string>
*/
protected static $cacheRelations = [
'documents',
];
/**
* Relation to Document
*
@ -58,19 +67,20 @@ class DocumentTag extends Model implements TranslatableModel
/**
* Get all Tags by category.
*
* @param string $category
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getTagsByCategoryInCurrentLocale($category): \Illuminate\Database\Eloquent\Collection
public static function getTagsByCategoryInCurrentLocale(string $category): \Illuminate\Database\Eloquent\Collection
{
$locale = App::getLocale();
return DocumentTag::query()
->whereHas('documents', function ($q) use ($locale) {
$q->whereNotNull("path->$locale");
})
->whereHas('documents.categories', function ($q) use ($locale, $category) {
$q->where("slug->$locale", $category);
})
->get();
return DocumentTag::getModelsCached()->load('documents.categories')->filter(function ($tag) use ($locale, $category) {
return $tag->documents->filter(function ($documents) use ($locale, $category) {
return !empty($documents->getTranslation('path', $locale, false)) && $documents->categories->contains(
fn ($cat) => $cat->slug === $category
);
})->isNotEmpty();
});
}
}

View file

@ -2,21 +2,22 @@
namespace App\Models;
use App\Contracts\TranslatableModel;
use Carbon\Carbon;
use App\Models\NewsTag;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use App\Traits\Models\HasCache;
use App\Enums\News\NewsStatusEnum;
use App\Helpers\TranslationHelper;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasTranslations;
use Illuminate\Support\Facades\App;
use App\Contracts\TranslatableModel;
use App\Traits\Models\HasUwilImages;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable;
/**
@ -137,6 +138,16 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
'unpublished_at' => 'datetime',
];
/**
* Relations should be included in the cache.
*
* @var array<string, string>
*/
protected static $cacheRelations = [
'categories',
'tags',
];
/**
* Perform any actions required after the model boots.
*
@ -340,16 +351,23 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
)->withTimestamps();
}
public static function getPublishedNewsByCategoryInCurrentLocale($category)
/**
* Get all published news by category.
*
* @param string $category
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getPublishedNewsByCategoryInCurrentLocale(string $category)
{
$locale = App::getLocale();
// ici mettre le cache avec la relation catégorie
return News::query()
return News::getModelsCached()
->where('status', NewsStatusEnum::published)
->with('categories', 'tags')
->whereNotNull("slug->$locale")
->whereHas('categories', function ($q) use ($locale, $category) {
$q->where("slug->$locale", $category);
->filter(function ($news) use ($category, $locale) {
return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains(
fn ($cat) => $cat->slug === $category
);
});
}
}

View file

@ -49,6 +49,15 @@ class NewsTag extends Model implements TranslatableModel
'slug'
];
/**
* Relations should be included in the cache.
*
* @var array<string, string>
*/
protected static $cacheRelations = [
'news',
];
/**
* Relation to Document
*
@ -74,14 +83,13 @@ class NewsTag extends Model implements TranslatableModel
{
$locale = App::getLocale();
return NewsTag::query()
->whereHas('news', function ($q) use ($locale) {
$q->whereNotNull("slug->$locale");
})
->whereHas('news.categories', function ($q) use ($locale, $category) {
$q->where("slug->$locale", $category);
})
->get();
return NewsTag::getModelsCached()->load('news.categories')->filter(function ($tag) use ($locale, $category) {
return $tag->news->filter(function ($news) use ($locale, $category) {
return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains(
fn ($cat) => $cat->slug === $category
);
})->isNotEmpty();
});
}
}

View file

@ -21,26 +21,24 @@ class NewsNextEventComponent extends Component
*/
public function __construct()
{
$locale = App::getLocale();
$newsCategory = NewsCategory::getModelsCached()
->filter(fn($category) => $category->getTranslation('slug', 'fr') === "actualites")
->first();
$newsCategory = Cache::remember('newsCategory', 86400, function () {
return NewsCategory::where('slug->fr', 'actualites')
->whereNull('deleted_at')
->value('slug');
});
$eventTag = NewsTag::getTagsByCategoryInCurrentLocale($newsCategory->slug)
->filter(fn($tag) => $tag->getTranslation('slug', 'fr') === "evenement")
->first();
$eventTagId = Cache::remember('eventTagId', 86400, function () {
return NewsTag::where('slug->fr', 'evenement')
->value('id');
});
$eventTagId = $eventTag ? $eventTag->id : null;
$this->nextEvents = News::getPublishedNewsByCategoryInCurrentLocale($newsCategory)
->whereHas('tags', function ($query) use ($eventTagId) {
$query->where('newsable_id', $eventTagId);
$this->nextEvents = News::getPublishedNewsByCategoryInCurrentLocale($newsCategory->slug)
->filter(function ($news) use ($eventTagId) {
return $news->tags->contains(
fn ($tag) => $eventTagId === $tag->id
);
})
->latest()
->take(3)
->get();
->sortByDesc('published_at')
->take(3);
}
/**

View file

@ -29,7 +29,7 @@
<div id="selected-filters" class="active-filters__list"></div>
<div class="active-filters__clear-wrap">
<div class="active-filters__item active-filters__item_clear">
<a class="active-filters__item-remove clear-all" data-param="clear-all"
<a class="active-filters__item-remove" data-category="{{ $postContainer['category'] }}" data-param="clear-all"
title="{{ ucfirst(__('front.buttons.clear_filters')) }}">✖</a>
{{ ucfirst(__('front.buttons.clear_filters')) }}
</div>
@ -72,6 +72,7 @@
const loader = wrapper.querySelector("#loader");
const section = wrapper.querySelector("#section");
const tblFilters = {};
let hasLoaded = false;
function isLoading(value = false) {
if (value) {
@ -143,19 +144,27 @@
initSelectedFilters();
}
document.addEventListener('DOMContentLoaded', function() {
ajaxLoadPosts();
document.addEventListener('scroll', function () {
if (hasLoaded) return;
loadMoreBtn.addEventListener('click', function() {
loadMoreBtn.classList.add('loading');
loadMoreBtn.disabled = true;
const wrapperPos = wrapper.getBoundingClientRect();
const isVisible = wrapperPos.top < window.innerHeight * 1.5;
setTimeout(() => {
ajaxLoadPosts();
loadMoreBtn.classList.remove('loading');
loadMoreBtn.disabled = false;
}, 3000);
});
if (isVisible) {
hasLoaded = true;
ajaxLoadPosts();
}
});
loadMoreBtn.addEventListener('click', function() {
loadMoreBtn.classList.add('loading');
loadMoreBtn.disabled = true;
setTimeout(() => {
ajaxLoadPosts();
loadMoreBtn.classList.remove('loading');
loadMoreBtn.disabled = false;
}, 1000);
});
function initFilters() {
@ -206,7 +215,7 @@
}
function initSelectedFilters() {
const items = document.querySelectorAll('.active-filters__item-remove');
const items = wrapper.querySelectorAll('.active-filters__item-remove');
items.forEach(item => {
item.addEventListener('click', function (e) {
@ -220,11 +229,15 @@
if (filterName === 'clear-all') {
Object.keys(tblFilters[category]).forEach(key => {
tblFilters[category][key] = [];
tblFilters[category][key] = Array.isArray(tblFilters[category][key]) ? [] : null;
});
} else if (filterName && value) {
const values = tblFilters[category][filterName] ?? [];
tblFilters[category][filterName] = values.filter(v => v !== value);
const tblItem = tblFilters[category][filterName];
if (Array.isArray(tblItem)) {
tblFilters[category][filterName] = tblItem.filter(v => v !== value);
} else if (tblItem === value) {
tblFilters[category][filterName] = null;
}
}
ajaxLoadPosts(true, tblFilters[category]);