5中拥有两种类型的用户

5中拥有两种类型的用户

本文介绍了在Laravel 5中拥有两种类型的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方式来处理有关不同类型用户的身份验证用户.

I am wondering if there is a better way of handling how I have my authenticated users in regards of different types of users.

我有一个基本用户和一个管理员用户.显然,基本用户只能访问基本页面,而管理员用户需要访问基本用户无法访问的其他页面.

I have a basic user and an administrator user. The basic user obviously will only have access to basic pages and the administrator user needs to have access to other pages that the basic user cannot have access to.

我一直在做的是:我在表中创建了一个super_user列并添加:

What I have been doing is: I created a super_user column in my table and adding:

    if(Auth::user()->super_user == 0) {
        return Redirect::to('/')->with('error', 'You do not have permission to access this page');
    }

我不希望基本用户能够访问的每个页面.现在,这可行,但是我开始将我的应用程序过渡到Laravel 5,并且我认为我可以采用另一种方式来处理此问题.

to each page that I do not want a basic user to be able to access. Now, this worked but I am starting to transition my apps to Laravel 5 and I am thinking there is a different way I can handle this.

推荐答案

处理您的用户角色的最佳方法是使用中间件.

Best way to handle user roles in your case is to use Middleware.

  1. 创建中间件:
namespace App\Http\Middleware;

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

class Admin
{
    /**
     * 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()->super_user) {
            return redirect->to('/')
                ->with('error', 'You do not have permission to access this page');
            }
        }

        return $next($request);
    }
}
  1. 将其添加到app\Http\Kernel.php:
protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\Admin',
];
  1. 在您的路线中使用中间件:
Route::group(['middleware' => ['admin']], function() {
    // your route
});

这篇关于在Laravel 5中拥有两种类型的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:32