php - Restrict route access to non-admin users -
goal
i'm trying create admin route restriction log-in users. i've tried check see if user log-in
, , if user type admin
, , if are, want allow them access admin route, otherwise, respond 404.
routes.php
<!-- route group --> $router->group(['middleware' => 'auth'], function() { <!-- no restriction --> route::get('dashboard','welcomecontroller@index'); <!-- admin --> if(auth::check()){ if ( auth::user()->type == "admin" ){ //report route::get('report','reportcontroller@index'); route::get('report/create', array('as'=>'report.create', 'uses'=>'reportcontroller@create')); route::post('report/store','reportcontroller@store'); route::get('report/{id}', array('before' =>'profile', 'uses'=>'reportcontroller@show')); route::get('report/{id}/edit', 'reportcontroller@edit'); route::put('report/{id}/update', array('as'=>'report.update', 'uses'=>'reportcontroller@update')); route::delete('report/{id}/destroy',array('as'=>'report.destroy', 'uses'=>'reportcontroller@destroy')); } } });
result
it's not working intended. throws 404 error - admin users.
you can use middleware simple case.
- create middleware:
php artisan make:middleware adminmiddleware
namespace app\http\middleware; use app\article; use closure; use illuminate\contracts\auth\guard; class adminmiddleware { /** * guard implementation. * * @var guard */ protected $auth; /** * create new filter instance. * * @param guard $auth * @return void */ public function __construct(guard $auth) { $this->auth = $auth; } /** * handle incoming request. * * @param \illuminate\http\request $request * @param \closure $next * @return mixed */ public function handle($request, closure $next) { if ($this->auth->getuser()->type !== "admin") { abort(403, 'unauthorized action.'); } return $next($request); } }
- add
app\http\kernel.php
:
protected $routemiddleware = [ 'admin' => 'app\http\middleware\adminmiddleware', ];
- use middleware in routes:
route::group(['middleware' => ['auth', 'admin']], function() { // routes });
Comments
Post a Comment