I have a middleware called 'AdminMiddleware', which is being used in the constructor of a class. For some reason the middleware is not called from the constructor, although the constructor function is being run. I tried doing a die dump on the adminMiddleware file but it seems like it just ignores this 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 cant use the middleware directly on the routes. Any help is appreciated, i am using laravel 5.1.
You need to do 2 things to enable middleware in the controller:
Register middleware in $routeMiddleware in your App\Http\Kernel.php
protected $routeMiddleware = [ 'admin' => 'App\Http\Middleware\AdminMiddleware', ];
Enable middleware in your controller, using middleware's key, not class name:
$this->middleware('admin');