Merge branch 'fix/storeDataInLocale' into 'develop'

fix: 🐛 data could be stored in the wrong locale when severl tabs where opened + some fixes

See merge request ldc-web/projets/ldc!130
This commit is contained in:
karl.muller 2026-02-10 15:10:27 +00:00
commit dd15044530
18 changed files with 113 additions and 34 deletions

View file

@ -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.

View file

@ -0,0 +1,62 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
class ForceLocale
{
/**
* This middleware forces the locale:
* - when it is changed from the back office
* - and when the form submitted in the request belongs to a different locale
*
* The issue occurred when two browser tabs were open in different locales:
* the data being saved could end up using the other tab’s locale.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next): mixed
{
$routeName = $request->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);
}
}

View file

@ -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);

View file

@ -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) {

View file

@ -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 (

View file

@ -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 (

View file

@ -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 (

View file

@ -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({
/>
)}
</div>
{(!data.is_issuu && model?.path) && (
{(!data.is_issuu && model?.path && originalDataPath) && (
<a
target="_blank"
className="text-blue-500 underline text-xs"

View file

@ -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] : ""
});
@ -42,7 +41,8 @@ export default function Form({
modelName,
action,
model,
post
post,
data
});
return (

View file

@ -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 : "",
@ -44,6 +43,7 @@ export default function Form({
action,
model,
post,
data
});
return (

View file

@ -118,7 +118,6 @@ export default function Form({
/** Form section */
const { post, setData, data, reset } = useForm({
_method: method === Methods.POST ? "post" : "put",
title: model?.title ? model?.title[locale] : "",
slug: model?.slug ? model?.slug[locale] : "",
content: model?.content ? model?.content[locale] : "",
@ -135,7 +134,8 @@ export default function Form({
modelName,
action,
model,
post
post,
data
});
function getFullSlugPath(

View file

@ -63,7 +63,6 @@ export default function Form({
/** Form section */
const { post, setData, data, reset } = useForm({
_method: method === Methods.POST ? "post" : "put",
seo_title: model?.seo_title?.[locale] ?? "",
seo_description: model?.seo_description?.[locale] ?? "",
title: model?.title?.[locale] ?? "",
@ -100,6 +99,7 @@ export default function Form({
action,
model,
post,
data
});
useEffect(() => {

View file

@ -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 (

View file

@ -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 (

View file

@ -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) => {

View file

@ -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 (

View file

@ -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: () => {

View file

@ -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');