Search code examples
laravelroutesmiddlewarelaravel-5.3

Using middleware in Laravel 5.3


I'm attempting to create a middleware in Laravel 5.3 that checks to see if the user is an admin so I can restrict some routes to admins only.

My Middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class IsAdmin
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next)
    {
        if( !\Auth::user()->hasRole('admin') ) {
            return redirect('login');
        }

        return $next($request);
    }
}

I register it in the Kernal, adding ti to the protected like the below:

protected $routeMiddleware = [
     ....
     'isadmin' => App\Http\Middleware\IsAdmin::class,
]

Then I try to secure my route with:

Route::resource('user', 'UserController')->middleware('isadmin');

But I get the error from my route file:

FatalThrowableError in web.php line 103:
Call to a member function middleware() on null

Solution

  • You should apply middleware with ::group():

    Route::group(['middleware' => 'isadmin'], function () {
        Route::resource('user', 'UserController');
    });