Omer Farooq
Omer Farooq

Reputation: 4084

Laravel's Middleware not working on Controller

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.

Upvotes: 6

Views: 35139

Answers (4)

Jaylord Ferrer
Jaylord Ferrer

Reputation: 95

Using Laravel Framework 9.46.0 doesn't work for me also with the key 'admin', changing it to 'administrator' or 'admin.only' works. it's like 'admin' is a reserved word.

Upvotes: 0

Johnny Fekete
Johnny Fekete

Reputation: 311

I ran into the same issue, and apparently route caching also caches middlewares.

So php artisan route:clear solved it in my case.

Upvotes: 15

Alex Chiang
Alex Chiang

Reputation: 1840

I have the same problem, and solve it by composer dump-autoload. My problem is change the file name and not regenerate the autoload. I hope it works for you.

Upvotes: 2

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

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

  1. Register middleware in $routeMiddleware in your App\Http\Kernel.php

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

  2. Enable middleware in your controller, using middleware's key, not class name:

    $this->middleware('admin');

Upvotes: 10

Related Questions