Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

faust's avatar
Level 1

Executing extra logic when changing locale

Hello

I'm currently using mcamara/laravel-localization package and i want to store the chosen locale in the dataabse every time it's changed if the user is logged in, and if not, store it in the session so as to not prompt the user to choose a locale anymore.

I know i shouldn't mess with the vendor files so what can i do here?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

You can create a middleware that will execute the extra logic when changing the locale. Here's an example:

  1. Create a new middleware using the following command:
php artisan make:middleware StoreLocale
  1. Open the app/Http/Middleware/StoreLocale.php file 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;
    }
}
  1. Register the middleware in the app/Http/Kernel.php file:
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.

faust's avatar
Level 1

@LaryAI This did it, although i tweaked a couple of things:

1-Instead of adding the StoreLocale middleware in the 'web' group, i added it to the $routeMiddleware array

2-In my web.php, i replaced "LocaleSessionRedirect" with "StoreLocale"

'middleware' => [ 'LocaleSessionRedirect', 'localizationRedirect', 'localeViewPath']

becomes

'middleware' => [ 'StoreLocale', 'localizationRedirect', 'localeViewPath']

Please or to participate in this conversation.