I have a middleware for setting the locale of my laravel application by getting the value from the session before each and every request.
I have a route that sets this variable,and I apply this middleware to all routes,including this one.
Here is my middleware:
namespace App\Http\Middleware;
use App;
use Closure;
use Session;
class LocaleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Session::has('locale')){
App::setLocale(Session::get('locale'));
}
return $next($request);
}
}
and here is my route for setting the language
public function setLang(string $lang)
{
Session::put('locale', $lang);
return back();
}
Now here is the problem.If I set that middleware to be global,in the kernel file,it does not take effect.The locale is not set properly.
If I manually apply that middleware to every route,it works.
If I assign that middleware to the web
middleware group,in the kernel file, that is automatically applied to all routes,it works as well.
This confuses me a lot.Please share your advice with me! thanks :)
I finally found an answer for that.
The middleware responsible for starting sessions is not a global middleware,it is only in the web
middleware group.Therefore,laravel was unable to access the session ,since my middleware was run before they were even started.