将新用户与其注册Laravel中的角色相关联

问题描述 投票:0回答:1

我在laravel中有一个应用,我有3个管理员,所有者,用户角色,我希望当用户注册时,他可以在用户和所有者之间进行选择,现在我将使用laravel / ui的注册表,我将保留它们我的关系和我的桌子

模型角色

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){

        return $this->belongsToMany('App\User');

    }
}

用户模型

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function roles(){

        return $this->belongsToMany('App\Role');
    }

    /* Validations */

    // The roles are received in the authorizeRoles variable, and they are validated if my role is valid or not, when accessing a page, the helpers abort generates an http exception and the user receives an error

    public function authorizeroles($roles){

        if($this->hasAnyRole($roles)){

            return true;

        }

        abort(401,'This action is unauthorized');
    }

    // Function, where we iterate (HasAnyRole) Enter the roles to check if you have any role

    public function hasAnyRole($roles){

        if(is_array($roles)){

            foreach($roles as $role){

              if($this->hasRole($role)){
                return true;
                }

            }

        }else{
            if($this->hasRole($roles)){
                return true;
            }
        }

        return false;

    }


     // HasRole function - We validate if our user contains the role for which it is asked -->

    public function hasRole($role){

        if($this->roles()->where('name',$role)->first()){
            return true;
        }

        return false;
    }


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
         'name', 'email', 'password', 'provider', 'provider_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

注册控制器

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

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 = RouteServiceProvider::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, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

我想知道如何在控制器中的两个角色之间进行过滤,并在选定的视图中绘制它们,谢谢您的支持

php html laravel eloquent
1个回答
0
投票

在控制器中

$roles = Role::whereIn('name', ['owner', 'user'])->get();

//And pass this roles in your view for example:

return view('user.create', compact('roles'); 

在视图中,形式:

<select name='role_id'>
  @foreach($roles as $role)
    <option value="{{$role->id}}">{{$role->name}}</option>
  @endforeach
</select>
© www.soinside.com 2019 - 2024. All rights reserved.