【问题标题】:Redirect authenticated users according to their role根据角色重定向经过身份验证的用户
【发布时间】:2016-07-14 18:00:31
【问题描述】:

我需要根据他们在应用程序中的角色重定向用户。在 MySQL 中,我在 Users 表中添加了“isAdmin”列来检查用户是否为管理员。我想出的唯一解决方案是根据用户的类型在同一个刀片上呈现 html。 例如。

@if(Auth::user()->isAdmin == 1)
<p>Hello, Admin</p>
//other html for admin

@else
//other html for users

是否有更好的方法可以让代码更美观、更高效,因为这看起来很乱? 我正在使用这个包 (https://github.com/acacha/adminlte-laravel),它使用 Laravel 的默认身份验证系统。

我想在用户登录过程中将用户重定向到两个不同的刀片,比如说 homeUsers.blade.php 和 admin.blade.php。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    逻辑在这里:最好的方法是创建两个表users和另一个roles,并将role_id作为外键放在users表中。然后创建一个关系角色belongsTo 用户。

    但是,在您的情况下,如果您有两个视图,并且您想为管理员显示一个,而为其他用户显示另一个,请遵循以下方法。

    创建两个您想在案例中使用的视图 1) admin 2) homeUsers

    @if(Auth::user()->isAdmin == 1)
      @include('admin') //admin.blade.php
    @else
     @include('homeUsers') //homeUsers.blade.php
    

    【讨论】:

    • 这对我来说似乎是最好的选择。我已经尝试过@Daniel 提出的解决方案,但它不适用于我的情况。也许我做错了什么,但现在我会使用你的解决方案。
    • 我忘了为可能有同样问题的其他人提及。它应该是 @include('admin') 而不是 @include('admin.blade.php')。 (不带扩展名)
    【解决方案2】:

    我不确定您使用的是哪个版本的 Laravel,但这似乎应该在您的中间件中。

    查看中间件中的RedirectIfAuthenticated.php。然后,您可以执行以下操作。

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            if (Auth::user()->role == 'Admin')
            {
                return redirect('/admin');
            }
            else
            {
                return redirect('/home')
            }
        }
    
        return $next($request);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 2020-02-18
      • 2019-04-25
      • 2020-02-22
      • 1970-01-01
      • 2015-04-20
      • 2010-12-21
      • 2013-10-25
      相关资源
      最近更新 更多