中间件在Laravel 5.2中没有按预期工作

时间:2016-08-03 07:27:06

标签: laravel laravel-5.2 laravel-routing

我已经制作了中间件来检查类是否按照url段存在并执行适当的任务。但是在触发中间件之前laravel捕获异常并抛出错误:

    ReflectionException in Route.php line 280:
Class App\Http\Controllers\cms\modules\asdfasdfsadf\asdfasdfsadfController does not exist

如果我死了并且在checkClass中间件上转储任何东西,那么只有在类存在时才转储该值。

应用中间件的路线是:

Route::group(['prefix' => PREFIX,'middleware'=>array('auth','role','checkClass')], function () {
    Route::group(['namespace' => 'cms' . '\\modules\\' . Request::segment(2) ], function () {

        Route::get('{module}/pages/{page}', Request::segment(4) . 'Controller@index');

        Route::get('{module}', Request::segment(2) . 'Controller@index');

        Route::get('{module}/{page}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::post('{module}/{page}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::get('{module}/{page}/{id}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::get('{module}/pages/{page}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::post('{module}/pages/{page}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::get('{module}/pages/{page}/{abc}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::post('{module}/pages/{page}/{abc}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));
    });
});

在这里,我们可以看到我根据网段动态创建了路由。这是我的checkClass中间件:

    <?php

namespace App\Http\Middleware;

use Closure;
use Request;
use Illuminate\Contracts\Auth\Guard;

class CheckClass
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (!class_exists('App\\Http\\Controllers\\cms\\modules\\'.Request::segment(2).'\\'.Request::segment(2).'Controller')) {

                return view("errors.404");

        } else {
            return $next($request);
        }

        return $next($request);
    }
}

在laravel根据路由搜索控制器类之前,不应该触发中间件吗?

1 个答案:

答案 0 :(得分:0)

中间件在Laravel找到路由后被解雇,因为它需要找出要使用的中间件(因为路由可以嵌套在多个组中等等)。

但是,此错误应默认为404。也许检查你是异常处理程序以确保它确实(并检查app.debug设置为false,因为它然后显示这样的异常,而不是只显示404.