简体   繁体   English

Laravel 用户角色访问内容查看

[英]Laravel user role access content in view

Have more than 150 views which has table content with the columns edit,view and add.拥有超过 150 个视图,其中包含包含编辑、查看和添加列的表格内容。 I want to restrict view according to user role.我想根据用户角色限制查看。 For ex.例如。 if the admin login, he can able to see all the options, if other he can only add not delete and edit.如果管理员登录,他可以看到所有选项,如果其他他只能添加不能删除和编辑。 How can we achieve this?我们怎样才能做到这一点? One way is calling different views for diff roles but this is not redudant and even there is more than 150 views.一种方法是为不同的角色调用不同的视图,但这并不是多余的,甚至有超过 150 个视图。

Conditional rendering in Blade Blade 中的条件渲染

You can check the user permission in your views and then decide what the user should be able to see and what not.您可以在视图中检查用户权限,然后决定用户应该能够看到什么,不能看到什么。

@if(Auth::user()->admin) 
    <input name="website_logo_url" type="text" />
@endif

Use middleware使用中间件

You can deny the access to certain views by using a middleware.您可以使用中间件拒绝对某些视图的访问。

  • Create the middleware with artisan: php artisan make:middlware MiddlewareName使用 artisan 创建中间件: php artisan make:middlware MiddlewareName
  • Define your middleware behavior by following Laravel Documentation: https://laravel.com/docs/5.5/middleware按照 Laravel 文档定义您的中间件行为: https ://laravel.com/docs/5.5/middleware

When u have a table with roles in your database you can do something like this in your web.php file当你的数据库中有一个带有角色的表时,你可以在你的 web.php 文件中做这样的事情

Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function() {

....

});

Then you make a middleware called "AdminMiddleware" or something like that.然后你制作一个名为“AdminMiddleware”或类似的中间件。

Every route you set inside that middleware group is restricted to what you put inside the middleware file.您在该中间件组中设置的每条路由都仅限于您放入中间件文件中的内容。 Take a look at this middleware file:看看这个中间件文件:

public function handle($request, Closure $next)
{
    $allowed_role_ids = [2];

    if (!in_array($request->user()->role_id, $allowed_role_ids))
    {
        return redirect('/')->with('flash', 'U heeft hier geen toegang voor');
    } elseif(Auth::guest()) {

        return redirect('/')->with('flash', 'U bent een gast, U heeft hier geen toegang voor');
    }

    return $next($request);
}

If the user's request role ID is not the allowed role_ID it is not allowed to access that route.如果用户的请求角色 ID 不是允许的 role_ID,则不允许访问该路由。 If it is, it will redirect to the desired route.如果是,它将重定向到所需的路线。 I hope this fixes your issue.我希望这可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM