Restrict route access to non-admin users

不羁的心 提交于 2019-12-02 21:13:40

You can use Middleware for this simple case.

  1. Create middleware:
php artisan make:middleware AdminMiddleware
namespace App\Http\Middleware;

use App\Article;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class AdminMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an 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);
    }
}
  1. Add it to app\Http\Kernel.php:
protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\AdminMiddleware',
];
  1. Use middleware in your routes:
Route::group(['middleware' => ['auth', 'admin']], function() {
    // your routes
});

This answer is about why your code doesn't work as expected. @limonte 's solution is correct and the best I can think of.

Your routes file is parsed to get your routes, and after that, those routes might be cached somewhere else.

Thus you shouldn't put any code that depends on the request (eg checking whether a User has sufficient rights to access a route).

In particular, you shouldn't use the following request dependent modules inside your routes.php (not exhaustive) :

  • Auth
  • DB or any kind of db queries that might depend on time
  • Session
  • Request

You should view your routes.php as part of your config, it just happens that it is written in php directly instead of some new language you have to learn.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!