简体   繁体   中英

attach role to a user upon registration laravel 5.4

I try to attach one of my roles as default role for users when they register, I tried different ways such as this post https://linustechtips.com/main/topic/802733-laravel-54-attaching-role-on-registration/ but nothing works:

the role I try to attach to registration form is name => user and id => 3 in case you want to help me with coding

Here is my registration form:

<?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']),
        ]);
    }
}

Thanks.

Did you use the php artisan make:auth to set up your authentication?

I've added the following to the app\\Http\\Controllers\\Auth\\RegisterController.php to assign all users the default role of '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;
}

And the following in User.php

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

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

here's how you can do it in a simple way ..

first of, you must have a request like

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

and so .. given the inputs , here's the function

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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