7.1 用户编辑页面
首先,修改控制器User.php
,
public function edit($id)
{
$user = UserModel::find($id);
return view('user/edit',compact('user'));
}
其次,在view
文件夹,新增edit.html
,特别注意邮箱是注册账号,不能改,要disabled
:
<div class="mb-3">
<label for="email" class="form-label">电子邮箱:</label>
<input type="email" required maxlength="255" value="{$user->email}" disabled class="form-control" placeholder="请输入您的电子邮箱" id="email" name="email">
</div>
同时,各种名称要改,还要把头像读过来。
<div class="offset-md-2 col-md-8 d-flex flex-column justify-content-center align-items-center">
<img src="{$user-">avatar}" alt="{$user->name}" width="200" class="img-thumbnail" />
</div>
方法必须是PUT,用下面代码做好伪装。
<form method="post" action="{:url('User/update',['id'=>$user->id])}">
{:token_field()}
<input type="hidden" name="_method" value="PUT">
留空为不修改密码:
<div class="mb-3">
<label for="password" class="form-label">密码:</label>
<input type="password" minlength="6" maxlength="255" class="form-control" placeholder="留空为不修改密码" id="password" name="password">
</div>
<div class="mb-3">
<label for="password_confirm" class="form-label">密码确认:</label>
<input type="password" minlength="6" maxlength="255" class="form-control" placeholder="密码确认" id="password_confirm" name="password_confirm">
</div>
最后,_header.html
要改链接。
7.2 用户信息编辑的业务编写
修改User.php
public function update(Request $request, $id)
{
$user = UserModel::find($id);
try {
validate([
'name|用户名' => 'require|max:255|token|unique:user,name,'.$id,
'password|密码' => 'min:6|confirm'
])->batch()->check($request->post());
$user->name = $request->post('name');
if ($request->post('password')){
$user->password = sha1($request->post('password').getSalt());
}
$user->save();
session('user',null);
if(Cookie::get('user_id')){
Cookie::delete('user_id');
}
return redirect((string) url('login.create'))->with('success','恭喜您,修改成功!请重新登录~');
} catch (ValidateException $e) {
if(!empty($errors = $e->getError())){
session('errors',$errors);
}
return redirect((string)url('User/edit',['id'=>$user->id]));
}
}
特别注意用户名修改这个id
的资料,不能修改为已经存在的。
感受:不是所有人都适合做老师。