From 35be275124f5e31ac4473f0c3d7311c125b4a898 Mon Sep 17 00:00:00 2001 From: K Muller Date: Tue, 10 Feb 2026 15:57:07 +0100 Subject: [PATCH] fix: :bug: data could be stored in the wrong locale when severl tabs where opened --- .../Controllers/Back/InputsController.php | 29 ++++++--- app/Http/Middleware/ForceLocale.php | 62 +++++++++++++++++++ app/Models/Document.php | 2 - bootstrap/app.php | 3 +- resources/ts/back/Pages/Companies/Form.tsx | 2 +- .../ts/back/Pages/CompanyActivities/Form.tsx | 3 +- .../ts/back/Pages/CompanySectors/Form.tsx | 2 +- resources/ts/back/Pages/Document/Form.tsx | 4 +- .../ts/back/Pages/DocumentCategory/Form.tsx | 4 +- resources/ts/back/Pages/DocumentTag/Form.tsx | 2 +- resources/ts/back/Pages/DynamicPages/Form.tsx | 4 +- resources/ts/back/Pages/News/Form.tsx | 2 +- resources/ts/back/Pages/NewsCategory/Form.tsx | 4 +- resources/ts/back/Pages/NewsTag/Form.tsx | 4 +- resources/ts/back/Pages/PageConfigs/Form.tsx | 4 +- resources/ts/back/Pages/Users/Form.tsx | 4 +- resources/ts/hooks/use-crud-submit.tsx | 11 +++- routes/web-back.php | 1 - 18 files changed, 113 insertions(+), 34 deletions(-) create mode 100644 app/Http/Middleware/ForceLocale.php diff --git a/app/Http/Controllers/Back/InputsController.php b/app/Http/Controllers/Back/InputsController.php index 0fea72b7..d3d8bbd0 100644 --- a/app/Http/Controllers/Back/InputsController.php +++ b/app/Http/Controllers/Back/InputsController.php @@ -43,8 +43,13 @@ class InputsController extends Controller return response()->json(['error' => 'Invalid model class'], 404); } + // Determine the field to display. $model = new $modelClass(); + $isTranslatable = method_exists($model, 'getTranslations'); + + $locale = app()->getLocale(); + $field = $validated['field'] ?? null; if (!$field) { $field = collect(['title', 'name', 'label']) @@ -52,10 +57,17 @@ class InputsController extends Controller ?? $model->getKeyName(); } + $getValue = function ($item) use ($field, $locale, $isTranslatable) { + if ($isTranslatable) { + return $item->getTranslation($field, $locale, false); + } + + return data_get($item, $field); + }; + // Fetch all cached models once. - $allItems = $modelClass::getModelsCached()->filter(function ($item) use ($field) { - $value = data_get($item, $field); - return $value !== null && $value !== ''; + $allItems = $modelClass::getModelsCached()->filter(function ($item) use ($getValue) { + return filled($getValue($item)); }); // Apply search and exclude filters @@ -63,11 +75,14 @@ class InputsController extends Controller ->when(!empty($validated['exclude']), function ($collection) use ($validated) { return $collection->reject(fn($item) => $item->id == $validated['exclude']); }) - ->when(!empty($validated['search']), function ($collection) use ($validated, $field) { - return $collection->filter(fn($item) => is_string($value = data_get($item, $field)) - && Str::contains(Str::lower($value), Str::lower($validated['search']))); + ->when(!empty($validated['search']), function ($collection) use ($validated, $getValue) { + return $collection->filter(function ($item) use ($validated, $getValue) { + $value = $getValue($item); + return is_string($value) + && Str::contains(Str::lower($value), Str::lower($validated['search'])); + }); }) - ->sortBy(fn($item) => data_get($item, $field)) + ->sortBy(fn ($item) => $getValue($item)) ->values(); // Paginate manually. diff --git a/app/Http/Middleware/ForceLocale.php b/app/Http/Middleware/ForceLocale.php new file mode 100644 index 00000000..10afdceb --- /dev/null +++ b/app/Http/Middleware/ForceLocale.php @@ -0,0 +1,62 @@ +route()?->getName(); + + if (! $routeName || ! Str::startsWith($routeName, 'back.')) { + return $next($request); + } + + // 1️⃣ Session + if (Session::has('lang')) { + $locale = Session::get('lang'); + } + // 2️⃣ FallBack + else { + $locale = config('app.fallback_locale'); + } + App::setLocale($locale); + + // 1. Is Post method or Inertia request ? + if ( + in_array($request->method(), ['POST', 'PUT', 'PATCH'], true) and + $request->headers->has('X-Inertia') + ) { + // 1. Request Locale + $requestLocale = $request->locale; + // 2. If prefix is not in supportedLocales + if (!in_array($requestLocale, app('laravellocalization')->getSupportedLocales(), true)) { + app()->setLocale(config('app.fallback_locale')); + } + // 3. Set new locale if locale and prefix are not the same + if ($requestLocale !== app()->getLocale()) { + app()->setLocale($requestLocale); + } + } + + return $next($request); + } +} diff --git a/app/Models/Document.php b/app/Models/Document.php index 8bae9504..b1213a3e 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -299,12 +299,10 @@ class Document extends Model implements TranslatableModel public function inertiaFill(array $attributes) { - // j'extrait issuPath et j'applique un traitement ensuite. $issuuPath = data_get($attributes, "issuu_path"); if($issuuPath) { $attributes['issuu_path'] = DocumentHelper::extractDocumentFromIssuIframe(data_get($attributes, "issuu_path")); - // dd($attributes); } $attributes = Arr::except($attributes, ['tags', 'categories']); $this->traitInertiaFill($attributes); diff --git a/bootstrap/app.php b/bootstrap/app.php index 0e49db19..ba7cd77f 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -18,7 +18,7 @@ return Application::configure(basePath: dirname(__DIR__)) ) ->withMiddleware(function (Middleware $middleware) { $middleware->web(append: [ - \Uwil\LaravelBackend\Middlewares\Lang::class, + \App\Http\Middleware\ForceLocale::class, \App\Http\Middleware\HandleInertiaRequests::class, \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class, \Uwil\LaravelBackend\Middlewares\LogoutUnpublishedUsers::class, @@ -32,7 +32,6 @@ return Application::configure(basePath: dirname(__DIR__)) $middleware->alias([ 'auth' => \Uwil\LaravelBackend\Middlewares\Authenticate::class, 'guest' => \Uwil\LaravelBackend\Middlewares\RedirectIfAuthenticated::class, - 'lang' => \Uwil\LaravelBackend\Middlewares\Lang::class, ]); }) ->withExceptions(function (Exceptions $exceptions) { diff --git a/resources/ts/back/Pages/Companies/Form.tsx b/resources/ts/back/Pages/Companies/Form.tsx index 614f802d..08c91101 100644 --- a/resources/ts/back/Pages/Companies/Form.tsx +++ b/resources/ts/back/Pages/Companies/Form.tsx @@ -34,7 +34,6 @@ export default function Form({ /** Form section */ const { post, setData, data, reset } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', name: model?.name, logo: model?.logo ?? "", responsable: model?.responsable ?? "", @@ -54,6 +53,7 @@ export default function Form({ action, model, post, + data }); return ( diff --git a/resources/ts/back/Pages/CompanyActivities/Form.tsx b/resources/ts/back/Pages/CompanyActivities/Form.tsx index aadd2e93..305563c8 100644 --- a/resources/ts/back/Pages/CompanyActivities/Form.tsx +++ b/resources/ts/back/Pages/CompanyActivities/Form.tsx @@ -12,7 +12,6 @@ import str from "@/hooks/use-string"; import InputError from "@/back/Components/InputError"; import { AppEnv, CompanyActivityModel } from "@/back/types/global"; import { useCrudSubmit } from "@/hooks/use-crud-submit"; -import { Methods } from "@/lib/enums"; export default function Form({ model, @@ -31,7 +30,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', name: model?.name ? model?.name[locale] : "", color: model?.color ?? null, published: model?.published, @@ -43,6 +41,7 @@ export default function Form({ action, model, post, + data }); return ( diff --git a/resources/ts/back/Pages/CompanySectors/Form.tsx b/resources/ts/back/Pages/CompanySectors/Form.tsx index 198ce892..982a68a6 100644 --- a/resources/ts/back/Pages/CompanySectors/Form.tsx +++ b/resources/ts/back/Pages/CompanySectors/Form.tsx @@ -30,7 +30,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', name: model?.name ? model?.name[locale] : "", published: model?.published, }); @@ -41,6 +40,7 @@ export default function Form({ action, model, post, + data }); return ( diff --git a/resources/ts/back/Pages/Document/Form.tsx b/resources/ts/back/Pages/Document/Form.tsx index b2779dd3..070f38c3 100644 --- a/resources/ts/back/Pages/Document/Form.tsx +++ b/resources/ts/back/Pages/Document/Form.tsx @@ -49,7 +49,6 @@ export default function Form({ /** Form section */ const { post, setData, data, reset } = useForm({ - _method: method === Methods.POST ? "post" : "put", name: model?.name ? model?.name[locale] : "", exercice: model?.exercice ? model?.exercice : "", status: model?.status ?? enumDocStatus.unpublished.value, @@ -69,6 +68,7 @@ export default function Form({ action, model, post, + data }); const originalDataPath = @@ -277,7 +277,7 @@ export default function Form({ /> )} - {(!data.is_issuu && model?.path) && ( + {(!data.is_issuu && model?.path && originalDataPath) && ( { diff --git a/resources/ts/back/Pages/NewsCategory/Form.tsx b/resources/ts/back/Pages/NewsCategory/Form.tsx index 0a20a37e..cc73c7b8 100644 --- a/resources/ts/back/Pages/NewsCategory/Form.tsx +++ b/resources/ts/back/Pages/NewsCategory/Form.tsx @@ -30,7 +30,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', name: model?.name ? model?.name[locale] : "", slug: model?.slug ? model?.slug[locale] : "", }); @@ -41,7 +40,8 @@ export default function Form({ modelName, action, model, - post + post, + data }); return ( diff --git a/resources/ts/back/Pages/NewsTag/Form.tsx b/resources/ts/back/Pages/NewsTag/Form.tsx index 9b3717f7..a1f585dc 100644 --- a/resources/ts/back/Pages/NewsTag/Form.tsx +++ b/resources/ts/back/Pages/NewsTag/Form.tsx @@ -31,7 +31,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', name: model?.name ? model?.name[locale] : "", slug: model?.slug ? model?.slug[locale] : "", color: model?.color ? model?.color : "" @@ -43,7 +42,8 @@ export default function Form({ modelName, action, model, - post + post, + data }); return ( diff --git a/resources/ts/back/Pages/PageConfigs/Form.tsx b/resources/ts/back/Pages/PageConfigs/Form.tsx index 57cf9400..ec9b098a 100644 --- a/resources/ts/back/Pages/PageConfigs/Form.tsx +++ b/resources/ts/back/Pages/PageConfigs/Form.tsx @@ -76,7 +76,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', label: model?.label ? model?.label[appEnv.locale] : "", view: model?.view, config: model?.config ? model?.config[appEnv.locale] ?? [] : [], @@ -88,7 +87,8 @@ export default function Form({ modelName, action, model, - post + post, + data }); const resetConfig = (localeData: string) => { diff --git a/resources/ts/back/Pages/Users/Form.tsx b/resources/ts/back/Pages/Users/Form.tsx index f74fd87f..2349e5f0 100644 --- a/resources/ts/back/Pages/Users/Form.tsx +++ b/resources/ts/back/Pages/Users/Form.tsx @@ -43,7 +43,6 @@ export default function Form({ /** Form section */ const { post, setData, data } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', first_name: model?.first_name, last_name: model?.last_name, email: model?.email, @@ -59,7 +58,8 @@ export default function Form({ action, model, post, - modelNameTrans: useTrans(`models.classes.user`) + modelNameTrans: useTrans(`models.classes.user`), + data }); return ( diff --git a/resources/ts/hooks/use-crud-submit.tsx b/resources/ts/hooks/use-crud-submit.tsx index 6ff60c7f..6a9de79b 100644 --- a/resources/ts/hooks/use-crud-submit.tsx +++ b/resources/ts/hooks/use-crud-submit.tsx @@ -3,6 +3,8 @@ import { FormEvent, useCallback } from "react"; import { useCrudMessages } from "./use-crud-messages"; import { route } from "ziggy-js"; import { useToast } from "./use-toast"; +import { InertiaFormProps, usePage } from "@inertiajs/react"; +import { AppEnv } from "@/back/types/global"; interface UseCrudSubmitParams { method: Methods; @@ -11,7 +13,8 @@ interface UseCrudSubmitParams { action: string; model?: { id?: number | string }; post: (url: string, options: any) => void; - modelNameTrans?: string + modelNameTrans?: string; + data: any; } export function useCrudSubmit({ @@ -21,8 +24,10 @@ export function useCrudSubmit({ action, model, post, + data, modelNameTrans }: UseCrudSubmitParams) { + const { locale } = usePage().props.appEnv as AppEnv; /** Set messages success/errors */ const messages = useCrudMessages({ method, modelName, modelNameTrans }); const { toast } = useToast() @@ -34,8 +39,10 @@ export function useCrudSubmit({ throw new Error("The method must be post or patch"); } - const routeUrl = route(`back.${modelRoute}.${action}`, model?.id); + data._method = method === Methods.POST ? "post" : "put" + data.locale = locale; + const routeUrl = route(`back.${modelRoute}.${action}`, model?.id); post(routeUrl, { preserveScroll: true, onSuccess: () => { diff --git a/routes/web-back.php b/routes/web-back.php index e62ad353..b79f28bd 100644 --- a/routes/web-back.php +++ b/routes/web-back.php @@ -23,7 +23,6 @@ use Uwil\LaravelCommon\Controllers\Controller; Route::prefix('admin') ->name('back.') - ->middleware(['lang']) ->group(function () { Route::get('/', fn() => redirect()->route('back.dashboard.index'))->name('redirect.dashboard');