1

I was trying to set a cookie to define a user-preferred language. I did that by having a link that leads to a helper controller :

/set-locale/{locale}

public function edit_locale($locale) {
    $durata= 2628000; // "forever"

    if (Cookie::has('locale')) {
        Cookie::queue(Cookie::forget('locale')); // If locale cookie is already defined, delete it
    }

    Cookie::queue("locale", $locale, $durata); // Set the cookie to either "en", "fr" or "ar"

    return redirect()->back();
}

I know this works correctly because if I do :

dd(Cookie::get('locale'));

It shows the correct locale chosen. So next step was to actually apply this chosen locale everywhere using a middleware, I named it "SetLocale" :

public function handle(Request $request, Closure $next)
{
    if (Cookie::has('locale')) {
        $locale = Cookie::get('locale'); // The cookie gotten here is all scrambled for some reason
    } else {
        // other logic for when cookie is not set (irrelevant for this question)
    }

    App::setLocale($locale);

    return $next($request);
}

But if I execute

dd(Cookie::get('locale'));

here in the middleware, it reads the cookie all scrambled. So my question is why is it doing that and how do I read the cookie correctly from here?

2 Answers2

1

use this to get cookie from request :

\Crypt::decrypt(Cookie::get('locale'))

or use

\Crypt::decryptString(Cookie::get('locale'))
0

Okay, esmaill's answer didn't work for me (Got a "unserialize(): Error at offset 0 of 43 bytes" error) but it did help point me in the right direction to solve it.

All I did was add 'locale' to the $except attribute of the EncryptCookies middleware and reset the cookie and now it's read correctly.