简体   繁体   中英

Laravel localization for custom error pages

I have custom error pages eg resources/views/errors/404.blade.php everything is working just fine but the localization is not working for error pages. If I change website language the error pages still show in default language I tried in many way but its not working, Can anyone please help me make this work thanks in advance.

I try to make it work via exception handler but don't know how to do that. I can apply language middleware is someone can tell me where is default routes for error pages.

Open app/exceptions/handler.php

find render function paste here

don't for get import this trait


use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


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);
}

You can also redirect to other pages in App\Exceptions\Handler.php . You can also assign using App::setLocale() . Like this:

public function render($request, Throwable $exception)
{
    App::setLocale('en_GB');
    /** @var \Symfony\Component\HttpKernel\Throwable $e */
    $e = $exception;
    $statusCode = $e->getStatusCode();
    return $this->isHttpException($exception) && $statusCode == 404 ?
        response()->view('frontend.pages.404') :
        parent::render($request, $exception);
}

thank you guys a little discussion with you guys fixed my problem I get the session's locale value in exception handler that worked for me I am answering it may be can help some one else. Below are the thing I did in App/Exception/Handler.php

use Session;

public function render($request, Throwable $exception)
{
    app()->setLocale(Session::get('locale'));
    return parent::render($request, $exception);
}

also i moved

\Illuminate\Session\Middleware\StartSession::class,

from web group to global group in kernal.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM