簡體   English   中英

將新用戶與其注冊中的角色相關聯 Laravel

[英]Relate a new user to a role from their registration Laravel

我在 laravel 有一個應用程序,我有 3 個管理員、所有者、用戶角色,我希望用戶注冊時可以在用戶和所有者之間進行選擇,現在我將使用 laravel / ui 的注冊表,我將離開他們我的關系和我的桌子

Model 作用

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){

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

    }
}

用戶 Model

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

寄存器 Controller

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

我想知道如何在我的 controller 中僅在兩個角色之間進行過濾,並在 select 中將它們繪制在我的視圖中,感謝您的支持

在 Controller

$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>

暫無
暫無

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

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