Sunday, January 17, 2016

Laravel 5.1 Restrict Routes Based on User's Access

Recently I was working on a Laravel project where we have three different types of users and based on their access levels, they are not allowed to view certain URLs. So if by chances user know the urls and try to view in browser, they should be redirected to not authorized page. So here in this blog I am going to explain how to do this in Laravel 5.1

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 App\Http\Middleware;

use Closure;

class AdminMiddleWare
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $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' => 'App\Http\Middleware\ 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');

As you can see in above code we have create route group and assigned AdminMiddleWare to group and specified all admin urls inside the group. 

Hope this helps you.

No comments:

Post a Comment