1
votes

I have a middleware which restrict access to route if the route is not allowed to him. I added it in:kernel.php

 protected $middleware = [ \App\Http\Middleware\MyMiddlware::class,]


 public function handle($request, Closure $next)
{
    $response = $next($request);
    $currentRoute = $request->route()->getName();
    $accessibleMenu = $this->menu->where('route_name', $currentRoute)->first();

  dd('middleware');

    if ($this->auth->check() && !is_null($accessibleMenu)) {

        $userRole = $request->user()->role()->first()->id;


        if (!is_null($userRole ) && $userRole ==1) {

            return $response;
        }
    }

    return Response::make(view('noPermission'), 404);
}

Route:

   Route::get('menu/list','MenuController@index')->name('menu-list');

controller function::

    public function index($parent_id = null)
{
     dd('executed');
    $menus = $this->menu->orderBy('id', 'DESC')->paginate(5000);

    return view('menu.index', compact('menus'));
}

Now for real: if role id is 2, the middleware should return 404 view without executing the route. But it prints executed string on screen!

1.If i deleted or comment:

 $response = $next($request);

it returns

Call to a member function getName() on null
  1. If i move route registration to

    'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\Activity::class, \App\Http\Middleware\MyMiddlware::class, ],

and comment:

 $response = $next($request);

then screen prints "middleware" and the middleware works

My question is why the middlware allow the function execution if i use this

 $response = $next($request);

in the first of the handle function? Why the middlware does not work and returns null for getName() if i use in protected $middleware = [] array ?

laravel says in kernel.php for - protected $middleware = []: * These middleware are run during every request to your application.

why is this allow even after i restrict access?

1

1 Answers

2
votes

I had difficulty reading thru this, however I think you want to change 2 lines:

remove $response = $next($request);

change return $response; to return $next($request);

I think you want to change these lines because $next($request) is the full execution.