Pankaj
Pankaj

Reputation: 10115

Authorization along with Authentication in Route.php : Laravel 5.1

I have below Route that checks if the user is authenticated and only then let them to access the page

<?php
Route::group([
    'middleware' => 'auth',
], function() {

    Route::get('/Categories-List', 'Skills\Category_Controller@index');
});

In my auth()->user(), there is RoleID to check if the user is Admin or with other role. I want to check if the RoleID is 1 then only let them to access the page.

Can I set Authorization along with Authentication in Laravel 5.1

Upvotes: 3

Views: 3292

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

Ok, so what you need is to create AdminMiddleware and add it to routes.

First, open your User model and add extra method into it:

public function isAdmin() 
{
   return $this->RoleID == 1;
}

Now run in console:

php artisan make:middleware AdminMiddleware

open your AdminMiddleware.php and change handle method so it should look like this:

if (!\Auth::user()->isAdmin()) {
    if ($request->ajax()) {
        return response('Admin account required.', 401);
    } else {
        return redirect('/'); // set here any url you need
    }
}

return $next($request);

Now open app/Http/Kernel.php and add into $routeMiddleware property new entry:

'isAdmin' => \App\Http\Middleware\AdminMiddleware::class,

Finally modify into your routes

'middleware' => 'auth',

into

'middleware' => ['auth', 'isAdmin'],

The order here is important, if you change order here, you will get unexpected Exception if user is not logged.

Depending on your needs you might also want to use only isAdmin middleware here in case for this route you want to make other redirection than in auth when user is not logged. In this case you need to merge methods from auth and isAdmin and fit it to your needs.

Upvotes: 8

Andrius
Andrius

Reputation: 5939

What you want to do is run multiple middlewares - one to auth the user and the other one to check his access level.

What you want to do is define the middlewares in the array like so:

<?php
Route::group([
    'middleware' => ['auth','isAdmin'],
], function() {

    Route::get('/Categories-List', 'Skills\Category_Controller@index');
});

You can see I've added a isAdmin middleware that would do the check that you need. You only need to create the middleware yourself.

Plenty of other info on middleware on routes here: http://laravel.com/docs/master/middleware#assigning-middleware-to-routes

Upvotes: 2

Related Questions