簡體   English   中英

在注冊laravel 5.4后將角色附加給用戶

[英]attach role to a user upon registration laravel 5.4

我嘗試在用戶注冊時將我的角色之一附加為默​​認角色,我嘗試了不同的方式,例如這篇文章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']),
        ]);
    }
}

謝謝。

您是否使用php artisan make:auth來設置身份驗證?

我已將以下內容添加到app \\ Http \\ Controllers \\ Auth \\ RegisterController.php中,以為所有用戶分配默認角色“ user”

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);
}

這是您可以通過簡單方式完成的方法..

首先,您必須有一個類似的要求

// $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()
    }
}
$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM