In this episode, we're tidying up our multilingual app by making sure the selected language actually sticks on every page request. We've already got a language dropdown that saves the user's choice in the session, but up until now, every new request still just defaulted to English—no matter what the user picked! To solve that, we roll up our sleeves and create some middleware that grabs the session value and sets the app locale for every request.
We talk about where to register this middleware so it has access to the session, and carefully place it right after the session starts but before anything else that needs the correct locale runs. Then we flesh out the middleware itself, using our handy language enum to safely fetch and assign the chosen language from the session or fall back to a default. With just a few lines, our app now remembers and uses the user's language preference correctly across all pages.
To wrap things up, we write a unit test for our middleware. We hit a small speed bump when we realize the test case doesn't boot the full Laravel app by default in unit tests, but show you how to fix that so our test can use app-specific helpers like app()->setLocale()
. Once that's sorted, we verify that the right language gets set from the session, and check that all our tests are green. By the end, you've seen how to lock in user language preference reliably, and properly test it too!