Before I wrote an post for the same topic, but it was written for Laravel 8. Now, I have updated it for Laravel 11.
Route set up
Open your route file routes\web.php and add the following code:
1 2 3 4
| Route::get('/lang/{locale}', function ($locale) { session()->put('locale', $locale); return redirect()->back(); });
|
Add middleware
1
| php artisan make:middleware Localization
|
Open the file app/Http/Middleware/Localization.php
and edit as the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <?php
namespace App\Http\Middleware;
use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\App;
class Localization {
public function handle(Request $request, Closure $next) { if (session()->has('locale')) {
App::setLocale(session('locale')); } return $next($request); } }
|
Then add the Localization middleware to the middlewareGroups section of bootstrap/app.php
file as the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use App\Http\Middleware\Localization;
return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__ . '/../routes/web.php', commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->appendToGroup('web', Localization::class); }) ->withExceptions(function (Exceptions $exceptions) { })->create();
|