Reputation: 634
I have this simple middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
use App;
class SetPageLanguage
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Session::has('language'))
{
$lang = Session::get('language');
App::setLocale($lang); // still don't know which one to use, but I'll figure it out ;)
app()->setLocale($lang);
}
return $next($request);
}
}
Which is supposed to run before every single request. So I added it to the kernel:
class Kernel extends HttpKernel
{
protected $middleware = [
...
\App\Http\Middleware\SetPageLanguage::class, // middleware for setting the language when loading a page
];
But it doesn't work. It never runs.
On the other hand, if I put it in routeMiddleware, like so:
protected $routeMiddleware = [
...
'localization' => \App\Http\Middleware\SetPageLanguage::class,
...
And call it on every route, like, for example:
Route::GET('/', 'AnonymController@home')->middleware('localization');
It works perfectly! But I don't want to have to do that. I want it to run automatically before every single request, like it is supposed to. What am I missing?
I'm quite new to laravel and Php, so I'm sure I'm not understandig something important.
I watched some tutorials, read a few articles and searched for the answer here on Stack Overflow. Still can't figure it out.
How can I make my middleware run before every single request?
Thank you.
Upvotes: 1
Views: 2673
Reputation: 35337
It likely is running, but global middleware run before route middleware. It's important to understand what the other middleware are doing and the order they are called.
If you look at the 'web'
middleware group, you'll see this middleware:
\Illuminate\Session\Middleware\StartSession::class,
Sessions are not instantly available in a Laravel app. The StartSession middleware is what starts sessions for web routes. API routes don't use sessions because they are stateless.
Therefore, this middleware likely belongs in the web group below the session middlewares since it relies on session data.
Upvotes: 3