0

在我的 Laravel 5.2 应用程序中,我有一个名为“cart”的自定义中间件,我用它来跟踪不同路线上的用户购物车内容。

它看起来像这样:

class CartMiddleware
{

    public function handle($request, Closure $next)
    {
        $cart = new Cart();
        $cart_total = $cart->total();

        view()->composer(['layouts.main'], function ($view) use ($cart_total) {
        $view->with('cart_total', $cart_total);
    });
    return $next($request);
}

}

Route::group(['middleware' => ['cart']], function () {
    Route::get('cart', 'CartController@show');
});

当我的应用程序引发 404 异常时,404.blade.php 视图无法呈现,因为它缺少$cart_total“购物车”中间件提供的内容。

有没有办法将此“购物车”中间件分配给我的异常?

  if ($e instanceof HttpException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.404', [], 404);
    }
    return parent::render($request, $e);
4

1 回答 1

0

在 Laravel 5.4 和可能一些较旧的版本中,您可以像这样修改文件app/exceptions/Handler.php和函数render

if( is_a( $exception, \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class ) ) {
    return redirect()->route( 'error_404' );
}

// ... old code in the function ...

这样,每个 404 错误都会被重定向到某些真实的路由,就像站点的其他路由一样。

您还可以提交当前请求中的任何数据,以显示目标的合理错误。

于 2017-07-30T12:33:13.663 回答