For this you have to use Laravel 5.1 HTTP middle ware. HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. So first of all create middleware. Go to your laravel application directory in terminal.
php artisan make:middleware AdminMiddleWare
What I did is I created additional column in my users table called access_level and defined three access level
1 = Admin
2 = User
Add following code to middleware we created.
namespace AppHttpMiddleware;
use Closure;
class AdminMiddleWare
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->user() == null){
return redirect(‘login’);
}
if ($request->user()->access_level != 1)
{
return redirect(‘not-authorized’);
}
return $next($request);
}
}
in the function handle we have added code to check access level. First of all if check if user is logged in by checking following condition.
$request->user() == null
So if there is no authenticated user we redirect to login and if user is logged in we check access level. If access level is not one we redirect them to not authorized page.
Now how will this middle ware works with routes. Go to your routes.php page.
Route::group([‘middleware’ => ‘AppHttpMiddleware AdminMiddleWare’], function()
{
Route::get(‘admin/login’,array(‘middleware’ => ‘auth’, ‘uses’ => ‘AdminController@index’));
Route::resource(‘admin-url1’, ‘AdminController’);
Route::resource(‘admin-url1’, ‘AdminController’);
Route::resource(‘admin-url1’, ‘AdminController’);
});