如何为 laravel 中的特定用户禁用 url?

how to disable the url for specific user in laravel?

我有一个管理员 table,其中有一些列,例如 idadmin_typename 等。这里我有两种类型的 admin_type : 一个是 "admin" 另一个是 "hod".

现在的问题是我希望使用 (admin_type == "admin") 登录的管理员能够访问所有管理 URL,但是当 admin_type == "hod" 我想限制用户可以访问的 URL。

我正在使用 Laravel 5.2。谁能帮我解决这个问题?

例如,如果 admin_type=="hod" 的用户访问这些链接

www.example.com/admin/add-user
www.example.com/admin/edit-user
www.example.com/admin/add-customer
www.example.com/admin/edit-customer

以及更多 URL,我想显示一些消息,例如 **You have no rights to access this link **

这是我的数据库结构:

我会为这样的用例实施 Middleware。只需在您的 Laravel 工作目录中执行 php artisan make:middleware yourNameHere,artisan 就会为您生成相应的中间件 class。

那么你需要这样的代码。如果用户不是管理员,这是一个带有 403 中止的简单 if 条件。

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()->admin_type != 'admin') {
            return abort(403, "No access here, sorry!");
        }

        return $next($request);
    }
}

你的路线文件(routes/web.php):

...
Route::group(["middleware" => 'admin'], function () {
       //Your admin routes should be declared here
});
...