Laravel Middleware not working on controller

I have a middleware called AdminMiddleware that is used in the constructor of a class. For some reason the middleware is not called from the constructor even though the constructor function is being invoked. I tried to dump the dying in the adminMiddleware file, but it looks like it just ignores that file.

namespace App\Http\Controllers\SuperAdmin;

    use Illuminate\Http\Request;

    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Auth;

        class dashboard extends Controller
        {
            protected $user;

            public function __construct()
                {
                    $this->middleware('admin');
                    $this->user = Auth::User();
                }

//Kernel.php
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'superadmin' => \App\Http\Middleware\SuperAdminMiddleware::class,
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
    ];

      

For some project requirements, I cannot use middleware directly on routes. Any help is appreciated, I am using laravel 5.1.

+3


source to share


3 answers


You need to do 2 things to enable middleware in your controller:



  • Register middleware in $ routeMiddleware in your app \ Http \ Kernel.php

    protected $ routeMiddleware = ['admin' => 'App \ Http \ Middleware \ AdminMiddleware',];

  • Include middleware in your controller using the middleware key and not the class name:

    $ this-> middleware ('admin');

+6


source


I have the same problem and solve it using the dump-autoload linker. My problem is changing the filename and not regenerating the autoload. Hope this works for you.



+1


source


I faced the same issue and obviously route caching caches middleware as well.

So php artisan route:clear

solved it in my case.

0


source







All Articles