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\[email protected]');
});
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
Answer
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.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?