简体   繁体   English

Laravel 5.6 用角色注册用户

[英]Laravel 5.6 register user with role

Hello i was following this tutorial你好,我正在关注本教程

https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/#comment-1889 https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/#comment-1889

i done everything ok and add some rules, a custom error page, and only admin can register new users.我做的一切都很好,并添加了一些规则,一个自定义错误页面,只有管理员可以注册新用户。 in the /admin view i can see all users register and the admin can delete this users.在 /admin 视图中,我可以看到所有用户注册,管理员可以删除这些用户。

i need two more roles, for users to see especific views, and i'm trying define the role in the register form so the admin can define who can see the a specific page.我还需要两个角色,供用户查看特定视图,我正在尝试在注册表中定义角色,以便管理员可以定义谁可以查看特定页面。 one role for executive user and one for premium user.一种用于执行用户的角色,一种用于高级用户的角色。

i was able to do that, but only by adding the relation in the database role_user table我能够做到这一点,但只能通过在数据库role_user 表中添加关系

any idea how to get this done by the register form?知道如何通过注册表来完成这项工作吗? without entering in the database table无需进入数据库表

I am going to assume you're using a Blade template.我假设您使用的是 Blade 模板。 Use the following to add a drop down for the Role select.使用以下内容为角色选择添加下拉列表。

<select name="role">
@foreach ( $roles as $role )
  <option value="${{role->id}}">{{ $role->name }}</option>
@endforeach
</select>

You'll need to provide your currently available Roles, from your Role Model (ha), to the view.您需要提供当前可用的角色,从角色模型 (ha) 到视图。 This can be done in your controller when rendering the view.这可以在渲染视图时在您的控制器中完成。

// Part of your controller
$roles = Role::all();
return view('your-view', [ 'roles' => $roles ]);

The key part here is return view('your-view', [ 'roles' => $roles ]) .这里的关键部分是return view('your-view', [ 'roles' => $roles ]) The second parameter in the view function is data to be passed to the view itself. view函数中的第二个参数是要传递给视图本身的数据。 See the Blade docs for more info.有关更多信息,请参阅Blade 文档

When you submit your form you can "attach" the role to your user model after it has been saved.当您提交表单时,您可以在保存后将角色“附加”到您的用户模型。

$user = new User();
// Assign user info here
$user->save();
$user->roles()->attach($request->role);
  • ->roles() is the model that belongs to User that we want to attach to. ->roles()是属于我们要附加到的 User 的模型。
  • ->attach($request->role) - $request->role is the ID of the Role we want to attach to the newly created User. ->attach($request->role) - $request->role是我们要附加到新创建的用户的角色的 ID。

You can read more in the docs about attaching and assigning various relationships to others.您可以有关附加和分配各种关系给他人的文档中阅读更多内容。

see this the path

this the path of registration form这是注册表单的路径

vendor > laravel > framework > src >Illuminate >Foundation > Auth > RegistersUsers.php

this is my code #example and this is the controller of registration form这是我的代码#example,这是注册表的控制器

  /**
 * Show the application registration form.
 *
 * @return \Illuminate\Http\Response
 */
public function showRegistrationForm()
{
    $show = model_rolepath::all();
    return view('auth.register')->with('roles',$show);
}

and this is my blade这是我的刀片

 <div class="input-group mb-3 {{ $errors->has('role') ? ' has-error' : '' }}">
      <select type="text" class="form-control"  value="{{ old('role') }}" required autofocus id="role" name="role" placeholder="Role">
      @foreach($roles as $key=>$role)
          <option value="{{$role->rolepath}}">{{ $role->rolepath }}</option>
        @endforeach
      </select>
      @if ($errors->has('role'))
        <span class="help-block">
          <strong>{{ $errors->first('role') }}</strong>
        </span>
      @endif
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-tasks"></span>
        </div>
      </div>
    </div>

Customise the registration form:自定义注册表单:

Generate the authentication scaffolding which comes bundled with Laravel.生成与 Laravel 捆绑在一起的身份验证脚手架。

php artisan make:auth

Now that we have added the role column to our User model we also need to add the input for the roles in our view so add the select tag input to resources/views/auth/register.blade.php registration form.现在我们已经将role列添加到我们的用户模型中,我们还需要在视图中添加角色的输入,因此将选择标记输入添加到resources/views/auth/register.blade.php注册表单。

<div class="form-group row">
    <label for="role" class="col-md-4 col-form-label text-md-right">Role</label>
    <div class="col-md-6">
        <select name="role" class="form-control" >
            <option value="admin">Admin</option>
            <option value="agent">Agent</option>
            <option value="customer">Customer</option>
        </select> 
    </div>
</div>

Customise User model and RegisterController:自定义 User 模型和 RegisterController:

Add the role column to fillable attribute on the User Model so that we can make use of the create() method in Register Controller.将角色列添加到用户模型的fillable属性,以便我们可以使用注册控制器中的create()方法。

//User.php
protected $fillable = [
    'name', 'email', 'password','role',
];

Now customize RegisterController.php which is in app/Http/Controllers/Auth directory to include our role input when creating a new user.现在自定义位于app/Http/Controllers/Auth目录中的RegisterController.php以在创建新用户时包含我们的role输入。

Add a validation rule for the role field:role字段添加验证规则:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
        'role' => 'required|in:admin,agent,customer', //validate role input
    ]);
}

Add role field to the create() method:将角色字段添加到create()方法:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'role' => $data['role'],
    ]);
}

Now you should be able to register users with different roles.现在您应该能够注册具有不同角色的用户。 We'll create at least one user per each role, and we will move on to implementing the access control logic.我们将为每个角色至少创建一个用户,然后我们将继续实现访问控制逻辑。

Set-up middlewares:设置中间件:

Middleware provides a convenient mechanism for filtering HTTP requests entering our application.中间件提供了一种方便的机制来过滤进入我们应用程序的 HTTP 请求。 For example, Laravel includes an auth middleware that verifies the user of your application is logged-in.例如,Laravel 包含一个auth中间件,用于验证您的应用程序的用户是否已登录。

We will create middlewares for each of our roles.我们将为每个角色创建中间件。

php artisan make:middleware Admin
php artisan make:middleware Agent
php artisan make:middleware Customer

Add the following code to respective middlewares which are in app/Http/Middleware folder:将以下代码添加到app/Http/Middleware文件夹中的相应中间件:

use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'admin') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'agent') {
        return redirect('/agent');
    }
    else {
        return redirect('/customer');
    }
}

Agent.php代理.php

use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'agent') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'customer') {
        return redirect('/customer');
    }
    else {
        return redirect('/admin');
    }
}

Customer.php客户.php

use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'customer') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'agent') {
        return redirect('/agent');
    }
    else {
        return redirect('/admin');
    }
}

Now let's register our middleware with Laravel.现在让我们用 Laravel 注册我们的中间件。 Add the middleware classes to $routeMiddleware property located in app/Http/Kernel.php :将中间件类添加到位于app/Http/Kernel.php $routeMiddleware属性中:

protected $routeMiddleware = [
    // ...
    'admin' => 'App\Http\Middleware\Admin',
    'agent' => 'App\Http\Middleware\Agent',
    'customer' => 'App\Http\Middleware\Customer',
];

Now you can apply these middlewares to routes or to the controller itself:现在您可以将这些中间件应用于路由或控制器本身:

web.php:网页.php:

Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('admin');

Route::get('/agent', function(){
    echo "Hello Agent";
})->middleware('agent');

Route::get('/customer', function(){
    echo "Hello Customer";
})->middleware('customer');

Or you can specify a middleware in a controller's constructor, like this:或者您可以在控制器的构造函数中指定一个中间件,如下所示:

public function __construct()
{
    $this->middleware('auth');  
    $this->middleware('admin');
}

Redirect User After Log-in:登录后重定向用户:

If you use Laravel's default login setup, you may want to redirect the user to his role specific page after he logs in. and you can do that by overriding the redirectTo() method in your LoginController.php.如果您使用 Laravel 的默认登录设置,您可能希望在用户登录后将其重定向到他的角色特定页面。您可以通过覆盖 LoginController.php 中的redirectTo()方法来实现。 Make sure you remove the $redirectTo property from your LoginController.php .确保从LoginController.php删除$redirectTo属性。

Add this to your LoginController.php:将此添加到您的LoginController.php:

protected function redirectTo( ) {
    if (Auth::check() && Auth::user()->role == 'customer') {
        return('/customer');
    }
    elseif (Auth::check() && Auth::user()->role == 'agent') {
        return('/agent');
    }
    else {
        return('/admin');
    }
}

This solution was provided by @kerneldev more info on github此解决方案由@kerneldev 在github上提供更多信息

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

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