使用 select 选项 Laravel 5.2 插入新记录时将数据添加到数据透视表 table

Adding data to a pivot table while inserting a new record using select option Laravel 5.2

问题来了:

我创建了一个 CRUD 系统,这样管理员就可以 create/read/update/delete 用户。 问题是我不能 select 在我的 CRUD 系统中为用户设置角色。任何帮助将不胜感激!

我将指出我正在使用的 3 个迁移:用户、角色和他们的枢轴 table user_role。

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email')->unique();
        $table->string('username')->unique();
        $table->string('password');
    });

Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('name', 40);
        $table->string('description', 255);
    });

Schema::create('user_role', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->integer('user_id');
        $table->integer('role_id');
    });

这是我的用户模型:

public function roles(){
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

这是我的榜样:

public function users(){
    return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}

我像这样在 RoleTableSeeder 中播种一些角色:

Role::create([
        'id'            => 1,
        'name'          => 'Admin',
        'description'   => 'Admin User.'
    ]);
    Role::create([
        'id'            => 2,
        'name'          => 'Vendor',
        'description'   => 'Vendor User.'
    ]);
    Role::create([
        'id'            => 3,
        'name'          => 'User',
        'description'   => 'Simple User.'
    ]);

这是创建用户的代码:

        {!! Form::open(['route' => 'admin.users.allusers']) !!}
        <div class="form-group">
            {!! Form::label('Username', 'Username:') !!}
            {!! Form::text('username',null,['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('E-mail', 'E-mail:') !!}
            {!! Form::text('email',null,['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('Role', 'Role:') !!}
            <select class="form-control" id="role" name="role">
                <option value="Administrator">Administrator</option>
                <option value="Vendor">Vendor</option>
                <option value="User" selected="selected">User</option>
            </select>
        </div>
        <div class="form-group">
            {!! Form::submit('Create', ['class' => 'btn btn-primary']) !!}
            <a href="{{ route('admin.users.allusers')}}" class="btn btn-primary">Back</a>
        </div>
        {!! Form::close() !!}

创建用户后,您需要显式初始化 roles 关系。

$user = User::create(Request::all()); //user needs to be saved first so that ID is known
$role = Role::whereName(Request::input('role'))->first();
$user->roles()->attach($role);