dimanche 25 décembre 2016

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

So here's the problem:

I created a CRUD system so an administrator can create/read/update/delete users. The problem is that I can't select a role for a user in my CRUD system. Any help would really be appreciated!

I will point out the 3 migrations I am using: users, roles and the pivot table for them 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');
    });

This is in my User model:

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

And this is in my Role model:

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

I seed some roles in RoleTableSeeder like this:

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.'
    ]);

This is the code to create a 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="" class="btn btn-primary">Back</a>
        </div>
        {!! Form::close() !!}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire