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.
source to share
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');
source to share