Laravel localization for custom error pages - laravel

I have custom error pages e.g. 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.

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

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

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

Related

customize ExceptionHandler in findOrFail error message

Good morning all,
Laravel v7.+
I made a
$user = User::findOrFail($id);
on my controller, it works well but when I have no result it sends me to a 404 page.
I would like to be able to do a return back with error message.
Some are talking about try catch.
Do you have any other solution to optimize?
Thank you, good day, stay home!
If you are having this issue in a single Controller only, you can use try catch
If you need a more general solution, you can work with the exception render method (https://laravel.com/docs/master/errors#render-method) on the ModelNotFoundException
public function render($request, Throwable $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}
Alternative to try/catch
$user = User::find($id);
if(!$user){
return redirect()->back()->with(['error' => 'Error message']);
}
... your other logic here

laravel 5 : how to create two types of 404 page depending on loggedin or not

I want to create two Layouts of 404 page depending upon whether user loggedin or out.
am using laravel 5.8.
I have tried #if (Auth::guest()) and #guest both inside ExceptionHandler->render and inside errors\minimal.blade.php
but none works.
inside app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)){
$guard = array_get($exception->guards(),0);
switch ($exception->getStatusCode()) {
case 404:
$guard=='guest'? return redirect('/login'):return view('frontend.error.404');
break;
}
return parent::render($request, $exception);
}
}
I have modified my App\Http\Kernel.php. And now i can access Auth inside my Exception\Handler.php
protected $middleware = [
**\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,**
];
Problem solved. Thanks Game07er for link

How to redirect users to another page with session messages while error occuring

I want to redirect users to admin page when any error occuring about the thujohn/twitter package. It throws Runtimeexception..
So I add couple code handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof \RuntimeException) {
return redirect()->route('admin.panel')
->with('message', 'Please try again later..')
->with('message_type','warning');
} else {
return parent::render($request, $exception);
}
}
But when I say that, it redirects user at all exceptions even at 404 errors or Trying to get property of non-object erros.. How can I fix this ? I want to redirect user for just relevant error
Or is there any way to do redirect user with condition like below.
if($exception->code == 436){
// it says member has protected access. I can't use it code property outside of the exception class
return redirect()->route('admin.panel')
->with('message', 'Specific error message')
->with('message_type','warning');
}
First of all go to Exceptions/Handler.php.
Here you can develope your exeptions.
This is my example on QueryException (you need to find by dd() your exception and its code):
use Illuminate\Database\QueryException; // REMEMBER TO USE PROPER INSTANCE
public function render($request, Exception $exception)
{
//dd($exception); <-- here you can catch and check type od exception
switch(true) {
case $exception instanceof QueryException:
if($exception->getCode() == '23000') {
return redirect(
route('get.dashboard.index')
)->with('warning', 'No record in database);
}
break;
}
}

Having a controller on 404 urls using Laravel 5

I need to have a custom controller triggered when user hits a not-existing url or when I programmatically force an App::abort(404).
How can I do it?
My 404 views need some data, and a simple blade View (or a ViewComposer) is not enough.
Thanks
PS catch-all urls is not functional, because they don't catch programmatically launched 404.
Edit the render function of App\Exceptions\Handler class and add something about 404 here:
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
// Do what you want...
// You can even use the $request variable
}
Full example:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
echo 'hello from 404 renderer';
dd($request); // Or you can a view.
}
return parent::render($request, $exception);
}
Try to return a redirect() to your custom Controller instead of a response() from the Handler's render() method if the exception is 404. You can retrieve the the page requested from the $request then right ?
Here is the sample:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
return redirect(route('route.to.custom.controller'))->with('request', $request);
}
return parent::render($request, $exception);
}
Hope that will help, cheers !

Internet not available exception in Laravel 5.2

I was trying to open Sandbox paypal page from my Laravel application and faced below issue
This issue came when internet connection was not available. Like we face 404 issue...for that we have 404 blade in View folder.
Is there any way to handle this exception so that we can show a user friendly page to user that Please check your internet connection
It doesn't not works when I write below code:
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
return response()->view('errors.InternetConnection');
}
but it works when I write
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
\App::abort(404);
}
I created a new blade called InternetConnection in error folder
You can listen for this exception in App\Exceptions\Handler#render. Just add this:
if ($e instanceof PayPalConnectionException) {
return response()->view('errors.404', [], 404);
}
Yes, you can! (https://laravel.com/docs/5.1/errors#the-exception-handler)
in your App\Exceptions\Handler:
...
public function render($request, Exception $e)
{
if ($e instanceof PayPalConnectionException) {
//my paypal exception
return response()->view('errors.payPalConnectionError', [], 404);
}
return parent::render($request, $e);
}
This will work:-
you need to create a folder named errors if not already exist in views and place blade file named 404.blade.php in it. and put your error template for 404 error in this blade. laravel will automatically use it when ever a 404 error will occur.
In your app/Exceptions/Handler.php edit render method as:
public function render($request, Exception $e)
{
if($e instanceof ValidationException) return response()->view('errors.abc');
return parent::render($request, $e);
}
Remember Don't forget to USE the Exception in your Handler.php
Like I am showing abc view for ValidationException So I am adding this line in my Handler.php class
use Illuminate\Validation\ValidationException;
Otherwise this won't work.

Resources