4
4
5
5
use App \Http \Repository \UserRepository ;
6
6
use App \Http \Requests \StoreUserRequest ;
7
+ use App \Role ;
7
8
use App \User ;
8
9
use Illuminate \Http \Request ;
9
10
use App \Http \Controllers \Controller ;
@@ -62,6 +63,16 @@ public function store(StoreUserRequest $request)
62
63
$ input = $ request ->all ();
63
64
$ model = new User ($ input );
64
65
if ($ model ->save ()) {
66
+
67
+ $ roles = $ request ['roles ' ]; // 获取输入的角色字段
68
+ // 检查是否某个角色被选中
69
+ if (isset ($ roles )) {
70
+ foreach ($ roles as $ role ) {
71
+ $ role_r = Role::where ('id ' , '= ' , $ role )->firstOrFail ();
72
+ $ model ->assignRole ($ role_r ); // Assigning role to user
73
+ }
74
+ }
75
+
65
76
return $ this ->out (200 , ['data ' => ['id ' => $ model ->id ]]);
66
77
} else {
67
78
return $ this ->out (4000 );
@@ -93,7 +104,9 @@ public function show(User $User)
93
104
public function edit ($ id )
94
105
{
95
106
$ data = User::findOrFail ($ id );
96
- return $ this ->out (200 , $ data );
107
+
108
+ $ roles = Role::get (); // 获取所有角色
109
+ return $ this ->out (200 , array_merge ($ data , $ roles ));
97
110
}
98
111
99
112
/**
@@ -107,13 +120,18 @@ public function edit($id)
107
120
*/
108
121
public function update (StoreUserRequest $ request , $ id )
109
122
{
110
- $ input = $ request ->only ('name ' , 'email ' , 'password ' );
111
- // var_dump($input);exit();
112
- // $model = new User();$model->save($input, ['id' => $id]);
113
- // 老版本更新操作如下,新版本先查询再更新
114
- // User::where('id', $id)->update($input)
115
- $ User = User::findOrFail ($ id );
116
- if ($ User ->update ($ input )) {
123
+ $ user = User::findOrFail ($ id );
124
+ // 新增角色操作
125
+ $ input = $ request ->only (['name ' , 'email ' , 'password ' ]); // 获取 name, email 和 password 字段
126
+ $ roles = $ request ['roles ' ]; // 获取所有角色
127
+
128
+ if ($ user ->fill ($ input )->save ()) {
129
+ if (isset ($ roles )) {
130
+ $ user ->roles ()->sync ($ roles ); // 如果有角色选中与用户关联则更新用户角色
131
+ } else {
132
+ $ user ->roles ()->detach (); // 如果没有选择任何与用户关联的角色则将之前关联角色解除
133
+ }
134
+
117
135
return $ this ->out (200 , ['data ' => ['id ' => $ id ]]);
118
136
} else {
119
137
return $ this ->out (4000 );
0 commit comments