#Session in middleware is empty V.11

6 messages · Page 1 of 1 (latest)

hushed topaz
#

Hello, I am trying to store a language choosed by user for following set of it on every request in the middleware. But even though its getting logged in the correct order, in the middleware the session is always empty.

web.php

<?php

use Illuminate\Support\Facades\Route;


Route::get('translations/{locale}', ['App\Http\Controllers\LocaleController', 'getMessages']);
Route::get('translations', ['App\Http\Controllers\LocaleController', 'getLocales']);
Route::post('translations/{locale}', ['App\Http\Controllers\LocaleController', 'changeLocale']);
changeLocale() in LocaleController.php 

    function changeLocale($locale, Request $request) {
        try {
            App::setLocale($locale);
            session(['locale' => $locale]);
            Log::info("saved ". $locale);
            $locale = session()->all();
            Log::info("Saved locale ". print_r($locale, true));


            return response()->json([
                'status' => 'success',
                'message' => 'Succesfully changed locale',
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while changing the locale',
                'error' => $e->getMessage()
            ], 500);
        }

    }


bootstrap/app.php

in attachment
Http/Middleware/CheckLocale.php

in attachment

Logs

in attachment

Maybe something is up with laravel middleware order? I am using database driver with sqlite database

nimble dew
#

The session is initialized by the "web" middleware group. So make sure you've added it to the routes, and that your middleware runs after "web".

hushed topaz
#

@nimble dew I suppose they are already in the web group

php artisan route:list -vv


  GET|HEAD   translations ....................................................................................................................................................... LocaleController@getLocales  
             ⇂ web
  GET|HEAD   translations/{locale} ............................................................................................................................................. LocaleController@getMessages  
             ⇂ web
  POST       translations/{locale} ............................................................................................................................................ LocaleController@changeLocale  
             ⇂ web```
or you mean smth else?

how should I change app.php to make it run after web as you say?
#

append specifically to web group worked for me

    ->withMiddleware(function (Middleware $middleware) {
        $middleware->appendToGroup('web', [
            CheckLocale::class
        ]);
    })
bitter comet