Show a 404 page if route not found in Laravel 5.1 - php

I am trying to figure out to show 404 page not found if a route is not found. I followed many tutorials, but it doesn't work.
I have 404.blade.php in \laravel\resources\views\errors
Also in handler.php
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
// redirect to form an example of how i handle mine
return redirect($request->fullUrl())->with(
'csrf_error',
"Opps! Seems you couldn't submit form for a longtime. Please try again"
);
}
/*if ($e instanceof CustomException) {
return response()->view('errors.404', [], 500);
}*/
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
If I enter wrong URL in browser, it returns a blank page. I have
'debug' => env('APP_DEBUG', true),
in app.php.
Can anyone help me how to show a 404 page if route is not found? Thank you.

I recieved 500 errors instead of 404 errors. I solved the problem like this:
In the app/Exceptions/Handler.php file, there is a render function.
Replace the function with this function:
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
switch ($e->getStatusCode()) {
// not authorized
case '403':
return \Response::view('errors.403',array(),403);
break;
// not found
case '404':
return \Response::view('errors.404',array(),404);
break;
// internal error
case '500':
return \Response::view('errors.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
} else {
return parent::render($request, $e);
}
}
You can then use views that you save in views/errors/404.blade.php, and so on.

> The abort method will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
abort(403, 'Unauthorized action.');
is your app_debug set to true? if that is the case, Laravel will throw the error with backtrace for debugging purposes, if you change the value to false, Laravel will show the default 404 page in the errors folder. That being said you can choose to use abort at any time you want. at the controller level or at the route level, it is totally up to you.
ie
Route::get('/page/not/found',function($closure){
// second parameter is optional.
abort(404,'Page not found');
abort(403);
});

#tester.Your problem has already been solved, try the command below in composer:
php artisan view:clear
Then try once more with an unknown URL. Because I have also faced the same error before.

There is no need for you to check the error type and manually render the 404 view. Laravel already knows to render the view with the HTTP error code that was thrown (404 = resources/views/errors/404.blade.php). Get rid of the extra check and it should work fine.
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
// redirect to form an example of how i handle mine
return redirect($request->fullUrl())->with(
'csrf_error',
"Opps! Seems you couldn't submit form for a longtime. Please try again"
);
}
return parent::render($request, $e);
}

I use the following in app/Exceptions/Handler.php (Laravel 5.2):
/**
* 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 ($e instanceof \ReflectionException OR $e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) //Si la ruta no existe, mostar view 404.
return response(view('errors.404'), 404);
return parent::render($request, $e);
}
And it looks like this:img

In apache you could be able to put this code in .htaccess file at your main directory and make sure that change AllowOverride Directive to all in httpd confg file
ErrorDocument 404 the\path\to\404.blade.php

In config folder app.php change the following code
'debug' => env('APP_DEBUG', true),
In App->Exception->Handler.php Replace Render Function With Below Code
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException)
{
return response()->view('errors.404', [], 404);
}
if ($exception instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
}
else {
return parent::render($request, $exception);
}
return parent::render($request, $exception);
}

If you want to redirect to the 404 page if the route is not found..
Route::fallback(function () {
return view('404');
});

Related

Prevent laravel message to be displayed and redirect the user to custom page issue in Laravel 5

I would like to catch somehow the laravel error, warning message. I don't want to disable them from the config/app.php file. I am using monolog to log some information.
This is my piece of code:
public function view($id){
try {
$tag = Tags::find(12313); // tags is a model
}catch(Exception $error){
echo 'error'; exit();
$this->log->logMessage(Logger::ERROR, $error->getMessage());
return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']);
}
}
$this->log is a class where I am using the monolog class to log information.
The fact is that right now , it doesn't go to the catch part . I don't get the error message. I'm getting this message from laravel:
Trying to get property of non-object (View: ......
I intentionally put the number 12313 there to see if it is working or not. And for some reason is not working and I am not redirected . The idea, if something happened I want to redirect the user to a specific page with a general error message. How can I achieve that ?
You can do it in laravel .You can handle erors in App\Exceptions\Handler class
public function render($request, Exception $exception)
{
if($exception instanceof NotFoundHttpException)
{
return response()->view('errors.404', [], 404);
}
if ($exception instanceof MethodNotAllowedHttpException)
{
return response()->view('errors.405', [], 405);
}
if($exception instanceof MethodNotAllowedHttpException)
{
return response()->view('errors.404', [], 405);
}
return parent::render($request, $exception);
}
find() method doesn't throw an exception if the record is not found. So do this instead:
public function view($id)
{
$tag = Tags::find(12313); // tags is a model
if (is_null($tag)) {
$this->log->logMessage(Logger::ERROR, $error->getMessage());
return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']);
}
}
Or use findOrFail() which will throw an exception if specified record is not found.
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown

how to show 500 internal Server error page in laravel 5.2?

I want to show the page 500 internal server error Page. when user had syntax error mistake in project can anyone help me? if i do some mistake in syntax i want to show that particular blade.
You need to create handler to catching FatalErrorExceptions in your handler like below code:
Handler
In app/Exceptions/Handler.php
public function render($request, Exception $e)
{
// 404 page when a model is not found
if ($e instanceof ModelNotFoundException) {
return response()->view('errors.404', [], 404);
}
// custom error message
if ($e instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
} else {
return parent::render($request, $e);
}
return parent::render($request, $e);
}
View
See resources/views/errors/500.blade.php. If not exist then create it.
You can get more detailed OR other ways from Laravel 5 custom error view for 500
In your resources/views/errors folder create a file named 500.blade.php.
Laravel makes it easy to display custom error pages for various HTTP
status codes. For example, if you wish to customize the error page for
500 HTTP status codes, create a resources/views/errors/500.blade.php. This file will be served on all 500 errors generated by your application.
The problem is that Laravel will only do this automatic rendering of error pages for exceptions that are instances of HttpException. Unfortunately when your server throws an error (method does not exist, variable undefined, etc) it actually throws a FatalErrorException. As such, it is uncaught, and trickles down to the SymfonyDisplayer() which either gives you the trace (debug true) or ugly one-liner 'Whoops, looks like something went wrong' (debug false).
To solve this you have add this to your render method to app/Exceptions/Handler
# /app/Exceptions/Handler.php
# use Symfony\Component\Debug\Exception\FlattenException;
# public function render($request, Exception $e)
$exception = FlattenException::create($e);
$statusCode = $exception->getStatusCode($exception);
if ($statusCode === 404 or $statusCode === 500) {
return response()->view('errors.' . $statusCode, [], $statusCode);
}
Docs
My solution is simple, just replace your render() method in Exceptions\Handler.php file with:
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
*
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($request->expectsJson()) {
return $this->renderJson($request, $exception);
}
if ($this->shouldReport($exception) && app()->environment('production')) {
$exception = new HttpException(500, $exception->getMessage(), $exception);
}
return parent::render($request, $exception);
}
It will show 500 page if app in production environment. You will need to have 500.blade.php view in your resources/views/errors folder.
// app/Exceptions/Handler.php
protected function prepareResponse($request, Exception $e)
{
if($this->isHttpException($e) === false && config('app.debug') === false) {
$e = new HttpException(500);
}
return parent::prepareResponse($request, $e);
}
Like #Amit said
The problem is that Laravel will only do this automatic rendering of
error pages for exceptions that are instances of HttpException.
So my solution is to replace whatever exception that is not HttpException by a HttpException.
in app\Exceptions\Handler create the following method:
protected function convertExceptionToResponse(Exception $e)
{
$e = FlattenException::create($e);
return response()->view('errors.500', ['exception' => $e], $e->getStatusCode(), $e->getHeaders());
}
it will override the one in the parent class (Illuminate\Foundation\Exceptions\Handler) that displays the whoops page.
In Laravel 5.4, you could override prepareException function in your app\Exception\Handler.php:
/**
* #inheridoc
*/
protected function prepareException(Exception $e)
{
$exception = parent::prepareException($e);
if(!config('app.debug')) {
if(!$exception instanceof HttpException && $this->shouldReport($exception)) {
$exception = new HttpException(500);
}
}
return $exception;
}

how to show error message if route not found in laravel 5.2

If I change route name from url then how can I show the error message in larvel 5.2.
Suppose I am showing users list using url lara.local.com/users and I change the route like lara.local.com/userswwwww. In that case how to show error message.
It will throw 404 Not Found. To display a custom view while a URL not found create a file named 404.blade.php in your resources/views/errors/ directory. Whatever you write on that file it will be displayed. No need to do anything else. Laravel will handle the rest.
You can use exception handler for handle route not found errors. Update app\Exception\Handler.php like
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($this->isHttpException($e))
{
if($e->getStatusCode()===404 || $e->getStatusCode()===405)
{
return response()->view('errors.not-found', [], 404);
}
return $this->renderHttpException($e);
}
return parent::render($request, $e);
}

404 Error Handling in Laravel 5.2.15

I am asking this question because I did not get reply after adding my comment in this question
laravel routing and 404 error
In the above answer, we can see below code to be used in filters.php
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
But, I think we don't have filters.php in latest version. Can somebody suggest better way to handle 404 error?
You don't need to do that anymore. Don't include that. What you do is put a view file (your 404 error view) called 404.blade.php in your resources/views/errors folder and Laravel will handle 404 errors for you.
take a look
http://www.jeffmould.com/2016/05/25/laravel-5-error-handling/
I just change this line App/Exceptions/Handler.php file.
public function render($request, Exception $e)
{
// the below code is for Whoops support. Since Whoops can open some security holes we want to only have it
// enabled in the debug environment. We also don't want Whoops to handle 404 and Validation related exceptions.
if (config('app.debug') && !($e instanceof ValidationException) && !($e instanceof HttpResponseException))
{
/******************here I changed**********************/
# return $this->renderExceptionWithWhoops($e);
return response()->view('errors.404', [], 404);
}
// this line allows you to redirect to a route or even back to the current page if there is a CSRF Token Mismatch
if($e instanceof TokenMismatchException){
return redirect()->route('index');
}
// let's add some support if a Model is not found
// for example, if you were to run a query for User #10000 and that user didn't exist we can return a 404 error
if ($e instanceof ModelNotFoundException) {
return response()->view('errors.404', [], 404);
}
// Let's return a default error page instead of the ugly Laravel error page when we have fatal exceptions
if($e instanceof \Symfony\Component\Debug\Exception\FatalErrorException) {
return \Response::view('errors.500',array(),500);
}
// finally we are back to the original default error handling provided by Laravel
if($this->isHttpException($e))
{
switch ($e->getStatusCode()) {
// not found
case 404:
return \Response::view('errors.404',array(),404);
break;
// internal error
case 500:
return \Response::view('errors.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
/******************here I changed**********************/
#return parent::render($request, $e);
}
if (config('app.debug') && !($e instanceof ValidationException) && !($e instanceof HttpResponseException))
{

laravel 5 custom 404

This is driving me crazy. I'm working with Laravel 5 and it appears that the docs for 4.2 and generating 404 pages does not work.
First, there is no global.php so I tried putting the following in routes.php:
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
This results in an error "method missing() not found"
Debug is set to false.
I've searched and searched but so far have found no information on setting 404 pages in Laravel 5. Would appreciate any help.
Go to resources/views/errors and create a 404.blade.php file with what you want on your 404 page and Laravel takes care of the rest.
if you want to have some global solution, you can do changes in /app/Exceptions/Handler.php by adding code bellow
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
$statusCode = $e->getStatusCode();
switch ($statusCode) {
case '404':
return response()->view('layouts/index', [
'content' => view('errors/404')
]);
}
}
return parent::render($request, $e);
}
In Laravel 5 you could simply put a custom 404.blade.php under resources/views/errors and that's it. For other errors like 500 you could try the following in your app/Exeptions/Handler.php:
public function render($request, Exception $e)
{
if ( ! config('app.debug') && ! $this->isHttpException($e)) {
return response()->view('errors.500');
}
return parent::render($request, $e);
}
And do the same for 500 HTTP Exeptions
I like the case statement approach but it has some issues going levels deep.
However, this catches all errors:
Route::any('/{page?}',function(){
return View::make('errors.404');
})->where('page','.*');
Laravel 5 already has a pre-defined render method(line 43) under app/Exceptions/Handler.php. Simply insert the redirection code before parent::render. Like so,
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException)
{
$e = new NotFoundHttpException($e->getMessage(), $e);
}
//insert this snippet
if ($this->isHttpException($e))
{
$statusCode = $e->getStatusCode();
switch ($statusCode)
{
case '404': return response()->view('error', array(), 404);
}
}
return parent::render($request, $e);
}
Note: My view is under resources/views. You can somehow put it anywhere else you want.
Lavavel 5.8
Create a file in resources/views/errors/404.blade.php and add this code.
#extends('errors::minimal')
#section('title', __('Not Found'))
#section('code', '404')
#if($exception)
#section('message', $exception->getMessage())
#else
#section('message', __('Not Found'))
#endif
Then in your controller you can use:
abort(404, 'Whatever you were looking for, look somewhere else');
I was looking for an answer to something else but thought I'd help in case someone else is looking for this.
run the command php artisan vendor:publish
you will see all publishable files. type in the number for laravel-errors
the error files are then published to resources/views/errors folder
set for Particulier prefix and with custom condition
Route::fallback(function(Request $request) {
if($request->is('practitioner/*')) {
return response()->view('errors.practitioner-404', [], 404);
} else if( $request->is('patient/*') ) {
return response()->view('errors.patient-404', [], 404);
} else {
abort(404);
}
});
You need to create errors folder inside resources/views and place your 404.blade.php file inside errors folder.
It will do the work. you do not need to edit handler.php file inside App/Exception folder.

Categories