funfelfonfafis funfelfonfafis - 6 months ago 21
PHP Question

Laravel. Edit user with relationship

I want make form edit user. For the present moment I can edit the data from the user table, but I would like to assign power to the user roles, from the table roles (dropdownlist).

Controller

public function index()
{
$users = User::with('roles')->get();
return view('pages.user', compact('users'));
}
public function update($id, Request $request)
{
$user = User::with('roles')->findOrFail($id);
$user->update($request->all());
return redirect('users');
}


Form

{!! Form::model($user, ['method' => 'PATCH', 'action'=>['UsersController@update', $user->id]]) !!}
<div class="form-group">
<div class="form-group">
{!! Form::label('name','Name: ') !!}
{!! Form::text('name', null, ['class'=>'form-control','placeholder'=>'Here, user name']) !!}
</div>
<div class="form-group">
{!! Form::label('roles','Roles: ') !!}
{!! Form::select('roles',['class'=>'form-control']) !!}
{!! Form::select('roles',$user,null,['class'=>'form-control']) !!}
//i try this but still not working

</div>
</div>


User table

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


Roles table

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

Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
});


Thx for help.

Answer Source

I think you want display all role into 'Role' droppdown, check below change of code: Controller

public function index()
{   
    //Get user detail
    $users = User::with('roles')->get();

    //Get all roles
    $userRole = Roles::lists('name','id');
    return view('pages.user', compact('users', 'userRole'));
}

Form

<div class="form-group">
    {!! Form::label('roles','Roles: ') !!}
    {!! Form::select('roles',$userRole, null,['class'=>'form-control']) !!}<!-- replace with $users['role_id'], if want to display selected role-->
</div>

Let me know if still not working!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download