Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

psyopus's avatar

dynamic routes and route names?

i added localization and use routes like:

Route::get('/', function () {
     return redirect('/en/home');
});

Route::group(     
    [
        'prefix' => App\Libraries\myLocalization::getLocale(),
    ],
    function() {

        Route::get('/home', 'HomeController@getHome')->name('home');          
    
        Route::group(
            [
                'prefix'     => 'admin',
                'middleware' => [
                    'auth',
                ],
            ],
            function() {
                Route::get('/', 'AdminController@getHome')->name('admin.home');     
                Route::resource('/users', '\App\Http\Controllers\UserController');
                Route::resource('/roles', 'RoleController');
                Route::resource('/permissions', 'PermissionController');                
            }
        );
    }
);

in getLocale i simply check if there is a preference (cookie/session/db) and if not locale gets set to requested locale (app()->request->segment(1)).

this works all fine but i noticed that calling such routes by name doesnt work any more.

i fear that my solution has the trade off that using route names just isnt possible anymore which is too bad.

but perhaps there is another way still?

i could just drop the segment detection to determine language and use a middleware to set locale but that has a downside that linking to an url in a certain language will result in a default language page.

eg: http://mysite.com/en/some-awesome-article will give desired result

http://mysite.com/some-awesome-article will redirected to that same page in the default language... since it cannot know what the original language was. and perhaps the article isnt even available in the default language.

another option could be something like:

                Route::get('/', 'AdminController@getHome')->name(App\Libraries\myLocalization::getLocale() . '.admin.home');   

but that feels eeeww...

any thoughts?

0 likes
38 replies
martinbean's avatar

@psyopus I’d make locale a route parameter:

Route::pattern('locale', '[a-z]{2}');

Route::get('/{locale}/home', 'HomeController')->name('home');

You’ll then probably need to create a new helper function that automatically sets this parameter:

function locale_route($name, $parameters = [], $absolute = true)
{
    // Get locale from cookie and prepend it to parameters
    $parameters = array_merge([
        'locale' => request()->cookie('locale'),
    ], array_wrap($parameters));

    return route($name, $parameters, $absolute);
}

Which you can then use in your controllers/views instead:

<a href="{{ locale_route('home') }}">{{ trans('messages.home') }}</a>
1 like
psyopus's avatar

@martinbean

this seemed ok at first but has severe implications for other code.

any code that doesnt know about the locale_route function calls the default route function and then fails with Missing required parameters for [Route: xxx.xxx] .

i cant possibly adapt all other thirdparty code that makes calls to route instead of the new locale_route so this gets very ugly.

you'd think i'm not the first person ever to try to implement localization with route segments.. right?

perhaps extending the route class is an option but i have virtually no experience with laravel framework.

i think for now i better just store the users locale preference somewhere internally and use that to set locale for translation... unless someone can point me in another direction?

36864's avatar

If you want every route to be handled by your new locale_route function, just override the route() helper to return locale_route.

psyopus's avatar

yes but that would be a laravel system file and could possibly be overwritten on a laravel update, no? (and minor version updates seem very frequent, eg: 5.5. already had 4 minor updates in the past 2 weeks)

36864's avatar

I'm fairly sure if you just redefine route() in the same file you're defining locale_route(), any call will go through that.

I haven't tested this, so I could be wrong, but it should be easy enough for you to try.

psyopus's avatar

well that would throw a cannot redeclare function exception.

only place it would work is adding the function to index.php (before laravel helper file gets loaded) but thats a hack even to dirty for me ;)

martinbean's avatar

@psyopus All the Laravel helper functions are wrapped in if (! function_exists()) calls, so I think if you define the route() function in your application, it’ll use your’s instead of the one that comes with Laravel.

martinbean's avatar

@psyopus So a new page on URLs was adding to the Laravel documentation which seems to cover this very topic!

https://laravel.com/docs/5.5/urls#default-values

So you could use the route() helper as normal, and then set the “default” for the {locale} parameter:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        URL::defaults([
            'locale' => $request->cookie('locale'),
        ]);

        return $next($request);
    }
}
psyopus's avatar

yes, i now included a file which gets loaded before laravels helper functions file and i thought that would be the end of it but i noticed that third party packages break now:

Missing required parameters for [Route: users.destroy] [URI: {locale}/portal/users/{user}

because they dont necessarily use that same route function:

{!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!}

and perhaps directly call:

app('url')->route($name, $parameters, $absolute);

as i do in my custom route function and therefor not get the extra param.

:(

i think i will drop this whole idea of segment based localization and just use a internal setting because i need to move on with my project.

perhaps will try to figure it out at some other time.

36864's avatar

I had missed that addition to the docs. thanks @martinbean. This will help me quite a bit in my current project.

psyopus's avatar

@36864

yes it works very nice.. but beware (perhaps stating the obvious) you have to take into account that you have to update your resources because they will get passed the $locale also as first param now.

    public function edit($id) {
        $user = User::findOrFail($id); //Get user with specified id

fails obviously..

so:

    public function edit($locale, $id) {
        $user = User::findOrFail($id); //Get user with specified id

i would rather have not receive the $locale at all in the controller but probably can come up with a work around for that as well.

psyopus's avatar

one more glitch with this.

it all seems to work fine with the default locale value except when a login session has expired.

in that case i get a:

Illuminate \ Routing \ Exceptions \ UrlGenerationException
Missing required parameters for [Route: login] [URI: {locale}/login].

i have no idea how to fix this.

anyone?

36864's avatar

That might classify as a bug if you defined a default for it. If I understand this correctly, the default parameters should be included regardless of how the route is called, but it looks like the auth module isn't playing well with it.

Consider raising an issue on github for this.

EDIT: I had this wrong. the defaults do need to be explicitly called, so what you need to do is make sure you're calling it in a middleware that is used by every request. Adding your default-setting middelware to the $middleware array in Kernel.php should do this.

psyopus's avatar

i assumed i took care of that by switching out the routes from Auth::routes(); to my routes and adding the {locale} to path.

web.php:

//Auth::routes();


Route::get('/', function () {
     return redirect('/' . App::getLocale() . '/home');
});

Route::get('/portal', function () {

     return redirect('/'. App::getLocale() . '/portal');
});


Route::group(
        
    [ 'middleware' => [ 'localizeurl'] ],

    function() {

        // Authentication Routes...
        $this->get('/{locale}/login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('/{locale}/login', 'Auth\LoginController@login');
        $this->post('/{locale}/logout', 'Auth\LoginController@logout')->name('logout');

        // Registration Routes...
        $this->get('/{locale}/register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('/{locale}/register', 'Auth\RegisterController@register');

        // Password Reset Routes...
        $this->get('/{locale}/password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
        $this->post('/{locale}/password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
        $this->get('/{locale}/password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
        $this->post('/{locale}/password/reset', 'Auth\ResetPasswordController@reset');
    

        Route::get('/{locale}/home', 'HomeController@getHome')->name('home');  

... rest of my non auth routes ...

        Route::group(
            ['middleware' => ['auth'] ],
            function() {
                Route::get('/{locale}/portal/', 'PortalController@getHome')->name('portal.home');    

... rest of my auth routes ...
                
            }
        );
    
    }
);

the middel ware:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;
use App\Libraries\PepLocalization;

class LocalizeUrl
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        dd('Yesy you hit the LocalizeUrl middleware...');

        URL::defaults(
           [
                'locale' =>  PepLocalization::setLocale( isset( $request->user()->locale ) ? $request->user()->locale : null )
           ] 
        );
        
        return $next($request);
    }
}

the thing is the middelware is always called except at that '[Route: login] [URI: {locale}/login].'

perhaps a bug after all?

36864's avatar
'locale' =>  PepLocalization::setLocale( isset( $request->user()->locale ) ? $request->user()->locale : null )

Can you dd($request->user())? I'm fairly sure this is supposed to be null when a user is trying to log in.

psyopus's avatar

yes it's most probably null at that moment, but the PepLocalization::setLocale() function always returns a the default app locale when null is passed in.

but... checking the value of "$request->user()" is to no use since the middelware never gets called in the first place when it borks... thats why i put:

dd('Yesy you hit the LocalizeUrl middleware...');

just to check if the middle got called and it didnt.

that's basically why it doesnt function as expected :(

perhaps there is some hidden routes that get called by the auth module.

36864's avatar

Sorry, I misunderstood your previous post.

Could you post the full stack trace for the exception that gets thrown?

psyopus's avatar
Illuminate\Routing\Exceptions\UrlGenerationException 
…/vendor/laravel/framework/src/Illuminate/Routing/Exceptions/UrlGenerationException.php17
54
Illuminate\Routing\Exceptions\UrlGenerationException forMissingParameters
…/vendor/laravel/framework/src/Illuminate/Routing/RouteUrlGenerator.php90
53
Illuminate\Routing\RouteUrlGenerator to
…/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php321
52
Illuminate\Routing\UrlGenerator toRoute
…/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php302
51
Illuminate\Routing\UrlGenerator route
…/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php782
50
 route
…/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php220
49
Illuminate\Foundation\Exceptions\Handler unauthenticated
…/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php180
48
Illuminate\Foundation\Exceptions\Handler render
…/app/Exceptions/Handler.php51
47
App\Exceptions\Handler render
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php83
46
Illuminate\Routing\Pipeline handleException
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php55
45
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php67
44
Illuminate\Foundation\Http\Middleware\VerifyCsrfToken handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
43
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
42
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php49
41
Illuminate\View\Middleware\ShareErrorsFromSession handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
40
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
39
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php63
38
Illuminate\Session\Middleware\StartSession handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
37
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
36
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php37
35
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
34
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
33
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php59
32
Illuminate\Cookie\Middleware\EncryptCookies handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
31
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
30
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php102
29
Illuminate\Pipeline\Pipeline then
…/vendor/laravel/framework/src/Illuminate/Routing/Router.php612
28
Illuminate\Routing\Router runRouteWithinStack
…/vendor/laravel/framework/src/Illuminate/Routing/Router.php571
27
Illuminate\Routing\Router dispatchToRoute
…/vendor/laravel/framework/src/Illuminate/Routing/Router.php549
26
Illuminate\Routing\Router dispatch
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php176
25
Illuminate\Foundation\Http\Kernel Illuminate\Foundation\Http\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php30
24
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php51
23
Barryvdh\Debugbar\Middleware\InjectDebugbar handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
22
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
21
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/genealabs/laravel-caffeine/src/Http/Middleware/LaravelCaffeineDripMiddleware.php17
20
GeneaLabs\LaravelCaffeine\Http\Middleware\LaravelCaffeineDripMiddleware handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
19
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
18
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/fideloper/proxy/src/TrustProxies.php56
17
Fideloper\Proxy\TrustProxies handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
16
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
15
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php30
14
Illuminate\Foundation\Http\Middleware\TransformsRequest handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
13
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
12
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php30
11
Illuminate\Foundation\Http\Middleware\TransformsRequest handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
10
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
9
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php27
8
Illuminate\Foundation\Http\Middleware\ValidatePostSize handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
7
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
6
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php46
5
Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode handle
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php149
4
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php53
3
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php102
2
Illuminate\Pipeline\Pipeline then
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php151
1
Illuminate\Foundation\Http\Kernel sendRequestThroughRouter
…/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php116
0
Illuminate\Foundation\Http\Kernel handle
…/public/index.php70

36864's avatar

Looks like the error is originated by the exception handler in the unauthenticated method at line 220.

    /**
     * Convert an authentication exception into a response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
                    ? response()->json(['message' => 'Unauthenticated.'], 401)
                    : redirect()->guest(route('login')); //< Line 220
    }

For triaging purposes, could you change that line to redirect()->to(route('login'))?

EDIT: Thinking about it some more, this may simply be a middleware call order problem. Can you try and change your middleware stack so that the localizeurl middleware is called before the rest?

psyopus's avatar

this is how route looks when it breaks:

Route {#252 ▼
  +uri: "{locale}/login"
  +methods: array:2 [▶]
  +action: array:7 [▼
    "middleware" => array:2 [▼
      0 => "web"
      1 => "localizeurl"
    ]
    "uses" => "App\Http\Controllers\Auth\LoginController@showLoginForm"
    "controller" => "App\Http\Controllers\Auth\LoginController@showLoginForm"
    "namespace" => "App\Http\Controllers"
    "prefix" => null
    "where" => []
    "as" => "login"
  ]
  +controller: null
  +defaults: []
  +wheres: []
  +parameters: null
  +parameterNames: null
  +computedMiddleware: null
  +compiled: CompiledRoute {#334 ▶}
  #router: Router {#25 ▼
    #events: Dispatcher {#26 ▶}
    #container: Application {#2 ▶}
    #routes: RouteCollection {#28 ▼
      #routes: array:6 [▶]
      #allRoutes: array:45 [▶]
      #nameList: array:38 [▶]
      #actionList: array:42 [▶]
    }
    #current: Route {#266 ▶}
    #currentRequest: Request {#42 ▶}
    #middleware: array:9 [▼
      "auth" => "Illuminate\Auth\Middleware\Authenticate"
      "auth.basic" => "Illuminate\Auth\Middleware\AuthenticateWithBasicAuth"
      "bindings" => "Illuminate\Routing\Middleware\SubstituteBindings"
      "can" => "Illuminate\Auth\Middleware\Authorize"
      "guest" => "App\Http\Middleware\RedirectIfAuthenticated"
      "throttle" => "Illuminate\Routing\Middleware\ThrottleRequests"
      "isAdmin" => "App\Http\Middleware\AdminMiddleware"
      "clearance" => "App\Http\Middleware\ClearanceMiddleware"
      "localizeurl" => "App\Http\Middleware\LocalizeUrl"
    ]
    #middlewareGroups: array:2 [▶]
    +middlewarePriority: array:6 [▶]
    #binders: []
    #patterns: []
    #groupStack: []
  }
  #container: Application {#2 ▶}
}

for comparison when it not breaks:

Route {#266 ▼
  +uri: "{locale}/portal"
  +methods: array:2 [▶]
  +action: array:7 [▼
    "middleware" => array:3 [▼
      0 => "web"
      1 => "localizeurl"
      2 => "auth"
    ]
    "uses" => "App\Http\Controllers\PortalController@getHome"
    "controller" => "App\Http\Controllers\PortalController@getHome"
    "namespace" => "App\Http\Controllers"
    "prefix" => null
    "where" => []
    "as" => "portal.home"
  ]
  +controller: PortalController {#345 ▶}
  +defaults: []
  +wheres: []
  +parameters: array:1 [▼
    "locale" => "nl"
  ]
  +parameterNames: array:1 [▼
    0 => "locale"
  ]
  +computedMiddleware: array:4 [▼
    0 => "web"
    1 => "localizeurl"
    2 => "auth"
    3 => Closure {#346 ▶}
  ]
  +compiled: CompiledRoute {#343 ▶}
  #router: Router {#25 ▼
    #events: Dispatcher {#26 ▶}
    #container: Application {#2 ▶}
    #routes: RouteCollection {#28 ▶}
    #current: Route {#266}
    #currentRequest: Request {#42 ▶}
    #middleware: array:9 [▼
      "auth" => "Illuminate\Auth\Middleware\Authenticate"
      "auth.basic" => "Illuminate\Auth\Middleware\AuthenticateWithBasicAuth"
      "bindings" => "Illuminate\Routing\Middleware\SubstituteBindings"
      "can" => "Illuminate\Auth\Middleware\Authorize"
      "guest" => "App\Http\Middleware\RedirectIfAuthenticated"
      "throttle" => "Illuminate\Routing\Middleware\ThrottleRequests"
      "isAdmin" => "App\Http\Middleware\AdminMiddleware"
      "clearance" => "App\Http\Middleware\ClearanceMiddleware"
      "localizeurl" => "App\Http\Middleware\LocalizeUrl"
    ]
    #middlewareGroups: array:2 [▶]
    +middlewarePriority: array:6 [▶]
    #binders: []
    #patterns: []
    #groupStack: []
  }
  #container: Application {#2 ▶}
}

a couple of differences:

in the former :

  +parameters: null
  +parameterNames: null
...
  +computedMiddleware: null

in the latter:

  +parameters: array:1 [▼
    "locale" => "nl"
  ]
  +parameterNames: array:1 [▼
    0 => "locale"
  ]
...
  +computedMiddleware: array:4 [▼
    0 => "web"
    1 => "localizeurl"
    2 => "auth"
    3 => Closure {#346 ▶}
  ]
36864's avatar
36864
Best Answer
Level 13

That is likely because an error is generated during the calls in the 'web' middleware group, which is first up in the call stack. It never finishes going through the group, so the group isn't computed. The parameters are only set in the "localizeurl" middleware, which isn't called at all because 'web' already broke everything.

Stick 'localizeurl' at the top of your 'web' middleware group and test the route. Since you always have a default, is there a strong reason not to call that middleware on every route anyway?

Note that if you want to use the same middleware to localize api routes (or more generally, routes that don't use the 'web' middleware group), you'll need to add it to the $middleware array rather than the 'web' middleware group, or also add it to the 'api' group.

1 like
psyopus's avatar

i actually have no idea how to stick it at the top... :o

i thought this was the way to do it:

Route::group(
        
    [ 'middleware' => [ 'localizeurl'] ],

im still pretty much a laravel newb.

psyopus's avatar

ok, i figured it out,

i only specified it in $routeMiddleware in the kernel.

but now i also added it to $middlewareGroups at the start and it works!

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\LocalizeUrl::class, 
            \App\Http\Middleware\EncryptCookies::class,

so you need to have it defined in both $middlewareGroups AND $routeMiddleware.

seems a bit counter intiutive since it definitly is a routing middelware.. right?

anyway, really a lot of thanks for your patience and help!!

36864's avatar

so you need to have it defined in both $middlewareGroups AND $routeMiddleware.

You can probably remove it from your group.

What matters is that it's called before any middleware that can redirect your request to a new route.

psyopus's avatar

nope, it only started working when i added it to the group.

moving it up to the beginning of the $routeMiddleware stack didnt fix it.

36864's avatar

Well now that is quite weird. Effectively that would mean you're calling the middleware twice.

I'll see if I can do some tests on this over the weekend and figure out what's going on.

I guess what matters is that it's working now.

psyopus's avatar

hold on,

tried again and also doing php artisan cache:clear

and now it always seems to work.

so this should do it: remove middelware from routes

remove middleware reference from $routeMiddleware in kernel

add middleware as first item in $middlewareGroups web array.

i guess really solved now. :)

thx again!

36864's avatar

Well, you saved me a few hours of troubleshooting something that wasn't actually broken. Thanks for the update.

Glad to help. Also, if in the future you add localized api routes to your application, make sure to also add your new middleware to the api route. (Are localized api paths even a thing?)

Next

Please or to participate in this conversation.