Laravel 5.6 如何在所有控制器中使用Session?
Hey there! I see you’ve been digging into Laravel session issues for your multi-language site, and you already know how to handle locale storage in a single controller—but making this work consistently across all controllers is where middleware becomes your best friend. Let’s walk through the exact steps to set this up properly:
Step 1: Create a Custom Locale Middleware
First, we’ll build a middleware that runs on every web request to set the app’s locale based on the session value. Run this Artisan command to generate the middleware file:
php artisan make:middleware SetLocale
Open the generated file at app/Http/Middleware/SetLocale.php and update the handle method with this logic (we’ll add validation to avoid invalid locale values):
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class SetLocale { public function handle(Request $request, Closure $next) { // Check if a locale exists in the session if ($request->session()->has('locale')) { // Validate the locale is in your supported list (adjust as needed) $allowedLocales = ['en', 'zh', 'fr']; $locale = in_array($request->session()->get('locale'), $allowedLocales) ? $request->session()->get('locale') : config('app.locale'); // Apply the locale to the entire application app()->setLocale($locale); } return $next($request); } }
Step 2: Register the Middleware
Next, we need to tell Laravel to use this middleware for all web requests. Open app/Http/Kernel.php and add the middleware to the web middleware group (since sessions are only enabled for web routes by default):
protected $middlewareGroups = [ 'web' => [ // ... other existing middleware (like EncryptCookies, VerifyCsrfToken) \App\Http\Middleware\SetLocale::class, ], // ... ];
This ensures the locale is set before any controller logic runs, so every controller will inherit the correct language setting.
Step 3: Add a Route to Switch Languages
You’ll need a way for users to change their language. Add this route to routes/web.php:
use App\Http\Controllers\LocaleController; Route::get('/switch-locale/{locale}', [LocaleController::class, 'updateLocale'])->name('locale.switch');
Then create the LocaleController to handle storing the selected locale in the session:
php artisan make:controller LocaleController
Update the controller’s updateLocale method:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class LocaleController extends Controller { public function updateLocale(Request $request, $locale) { $allowedLocales = ['en', 'zh', 'fr']; if (in_array($locale, $allowedLocales)) { $request->session()->put('locale', $locale); } // Redirect back to the previous page return redirect()->back(); } }
Step 4: Verify Global Functionality
Now, across any controller in your app, you can access the stored locale directly:
// Get the locale from session $currentLocale = session('locale'); // Or get the active app locale (already set by the middleware) $activeLocale = app()->getLocale();
You don’t need to call session()->keep('locale') unless you’re explicitly trying to prevent it from being cleared—session values persist by default until they’re manually removed or the session expires.
This approach ensures your locale setting is applied consistently across controllers, views, and even Laravel’s built-in localization features (like translated validation messages or language files).
内容的提问来源于stack exchange,提问作者ronrun

