You can create a middleware that will execute the extra logic when changing the locale. Here's an example:
- Create a new middleware using the following command:
php artisan make:middleware StoreLocale
- Open the
app/Http/Middleware/StoreLocale.phpfile and add the following code:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect;
class StoreLocale extends LocaleSessionRedirect
{
public function handle($request, Closure $next)
{
$response = parent::handle($request, $next);
if (Auth::check()) {
// Store the chosen locale in the database
Auth::user()->update(['locale' => app()->getLocale()]);
} else {
// Store the chosen locale in the session
Session::put('locale', app()->getLocale());
}
return $response;
}
}
- Register the middleware in the
app/Http/Kernel.phpfile:
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\StoreLocale::class,
],
// ...
];
Now, every time the locale is changed, the middleware will store the chosen locale in the database if the user is logged in, or in the session if not.