Localizing the Breniapp: From Session to User Database
The Breniapp project aims to streamline [description]. Recently, we tackled an issue with the locale switcher that was causing inconsistencies in how user locales were being handled.
The Problem
Previously, the locale selected by a user was only being saved in the session and a cookie. This approach relied on a two-step redirect chain through a LocaleController. The SetLocale middleware prioritizes locale settings in the following order: user database > tenant locale > session. In environments with tenant-specific locales, the session value was being overridden, leading to a frustrating user experience.
The Solution
To address this, we modified the locale switcher to directly save the user's locale preference to their record in the database. This ensures that the user's chosen locale has the highest priority and persists across sessions.
Here's a simplified example of how the locale is now saved:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class LocaleController extends Controller
{
public function setLocale(Request $request, string $locale)
{
/** @var User $user */
$user = $request->user();
$user->locale = $locale;
$user->save();
return redirect()->back();
}
}
In this example, the setLocale method receives the desired locale and updates the locale column in the user's database record. This ensures that the user's preference is persisted and takes precedence over other locale settings.
Benefits
- Persistence: User's locale preference is now stored in the database and persists across sessions.
- Consistency: The user's locale is prioritized, preventing it from being overridden by tenant settings.
- Simplified Logic: Removed the fragile redirect chain, resulting in cleaner and more maintainable code.
The Takeaway
When dealing with user preferences, storing them directly in the database ensures persistence and consistency. This approach eliminates potential conflicts and simplifies the overall application logic, contributing to a better user experience.