在注册层5.4上将角色附加到用户

时间:2017-07-07 01:42:24

标签: php laravel laravel-5

我尝试将我的一个角色作为用户注册时的默认角色附加,我尝试了不同的方式,例如此帖子https://linustechtips.com/main/topic/802733-laravel-54-attaching-role-on-registration/,但没有任何作用:

我尝试附加到注册表单的角色是name => userid => 3,以防您想要帮我编码

这是我的注册表格:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'fname' => 'required|string|max:255',
            'lname' => 'required|string|max:255',
            'username' => 'required|string|min:4|max:255|unique:users',
            'gender' => 'required',
            'city' => 'sometimes|string|max:255',
            'province' => 'sometimes|string|max:255',
            'country' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'fname' => $data['fname'],
            'lname' => $data['lname'],
            'username' => $data['username'],
            'gender' => $data['gender'],
            'city' => $data['city'],
            'province' => $data['province'],
            'country' => $data['country'],
            'phone' => $data['phone'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

感谢。

3 个答案:

答案 0 :(得分:2)

您是否使用php artisan make:auth设置身份验证?

我已将以下内容添加到app \ Http \ Controllers \ Auth \ RegisterController.php中,为所有用户分配默认角色&#39; user&#39;

protected function create(array $data)
{
    $role = Role::where('name', 'user')->first();

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user->assignRole($role);

    return $user;
}

以及User.php中的以下内容

public function roles()
{
    return $this->belongsToMany(Role::class);
}

public function assignRole(Role $role)
{
    return $this->roles()->save($role);
}

答案 1 :(得分:0)

这是你如何以一种简单的方式做到这一点..

首先,你必须有一个像

这样的请求
// $request->id ( integer )
// $request->fname ( string )
// $request->lname ( string )
// $request->roles ( array )(assuming user and role have many to many relation)

等等..给定输入,这是函数

protected function roleValidator(array $data)
{
    return Validator::make($data, [
        'roles' =>  'required|array|min:1',
    ]);
}

public function editUser(Request $request)
{
    // FIRST VALIDATE INPUT ROLES
    $roles = $request->only('roles');
    // CHECK IF HAVE ATLEAST ONE HAS BEEN SELECTED
    $roleValidate = $this->roleValidator($roles);
    if (!$roleValidate->fails())
    {
        $request->roles = array_unique($request->roles);
        $roles = Role::orderBy('id','asc')->get(['id']);
        $roleList = array();
        foreach($roles as $role) { array_push($roleList,$role->id); }
        // CHECK IF ALL INPUTS ARE VALID ROLES IN THE DB
        if(count(array_intersect($request->roles, $roleList)) == count($request->roles))
        {
            // VALIDATE YOUR PROFILE
            .....
            $user = User::find($request->userID);
            $user->fname = $request->fname;
            $user->lname= $request->fname;
            $user->roles()->sync($request->roles);
            $user->save();
        }
        else
        {
            // INVALID ROLE DETECTED!
        }
    }
    else
    {
        // SHOW $roleValidate->errors()->all()
    }
}

答案 2 :(得分:0)

$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$role = new App\Role(['role' => 1]);
$user->roles()->save($role);
return $user;

来源:https://laracasts.com/discuss/channels/laravel/attach-role-to-a-user-upon-registration?page=1