You mean auto detect or allow a user to select?
Both are pretty standard.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I would like to be able to write functions like the one below that will switch the locale for the users session. I don't know if that is possible yet, or maybe the locale get set and stored in a cookie or something.
public function en()
{
setLocale(en);
return back();
}
public function es()
{
setLocale(es);
return back();
}
Right now my locales work great except I have to manually go into 'config/app.php' and manually switch the locale variable from 'es' to 'en' when I want to switch. There has got to be an easier way.
@fbc Sorry for my raw response. Didn't know that you were a beginner. Here is a kind of guide. Hope it helps.
Try this:
// Routes routes/web.php
Route::get('en', function() {
session(['locale' => 'en']);
return back();
});
Route::get('es', function() {
session(['locale' => 'es']);
return back();
});
// Middleware app/Http/Middleware/SetLocale.php
<?php
namespace App\Http\Middleware;
use Closure;
class SetLocale
{
protected $supported_languages = ['en', 'es'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(!session()->has('locale')) {
session(['locale' => $request->getPreferredLanguage($this->supported_languages)]);
}
app()->setLocale(session('locale'));
return $next($request);
}
}
// Registration App/Http/Kernel.php
Add the middleware to web array in your App/Http/Kernel.php file
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SetLocale::class, // here is the line
],
Now in order to change the locale you can use for example:
<a href="/en">English</a>
<a href="/es">Spanish</a>
Please or to participate in this conversation.