简体   繁体   中英

Show a 404 page if route not found in Laravel 5.1

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

在 apache 中,您可以将此代码放在主目录的 .htaccess 文件中,并确保在 httpd 配置文件中将 AllowOverride Directive 更改为 all

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

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