allyfai allyfai - 4 months ago 21
PHP Question

Laravel localization in 404 page

Hello I have an issue with laravel localization

I've made language switcher and currently selected language doesn't work on 404 pages (it works if I return abort(404) in controller manualy), it always shows content on default locale defined in config/app.php

My middleware code

<?php
namespace App\Http\Middleware;

use Closure;

class SetLanguageCookie
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->hasCookie('language')) {
$cookie = $request->cookie('language');
app()->setLocale($cookie);

return $next($request);
} else {
$response = $next($request);
$response->withCookie(cookie()->forever('language', 'en'));
return $response;
}
}
}


Any ideas how can I make this working? So all automaticaly shown 404 pages show content in currently selected language?

Answer

Fixed it with help of @ArthurSamarcos

app/Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if($request->hasCookie('language')) {
        // Get cookie
        $cookie = $request->cookie('language');
        // Check if cookie is already decrypted if not decrypt
        $cookie = strlen($cookie) > 2 ? decrypt($cookie) : $cookie;
        // Set locale
        app()->setLocale($cookie);
    }

    if($e instanceof NotFoundHttpException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $e);
}
Comments