在Laravel中,超级用户如何使用用户ID更新特定用户

时间:2019-03-28 08:54:56

标签: php laravel

我正在创建一个管理部分,超级用户需要在其中编辑具有特定ID的其他用户详细信息。像User :: create一样,如何更新用户详细信息?

if( empty($user_id) ){
    User::create([
        'name' => $data['name'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'mobile' => $data['mobile'],
        'role' => $data['role'],
        'password' => Hash::make($data['password']),                    
    ]);     
}else{                                                       
    //update user details
}

3 个答案:

答案 0 :(得分:4)

有两种选择:

这里是一个:

if (empty($user_id) ){
      User::create([
         'name' => $data['name'],
         'lastname' => $data['lastname'],
         'email' => $data['email'],
         'mobile' => $data['mobile'],
         'role' => $data['role'],
         'password' => Hash::make($data['password']),                    
      ]);

} else{                                                       
      User::where('id', $user_id)->update([
         'name' => $data['name'],
         'lastname' => $data['lastname'],
         'email' => $data['email'],
         'mobile' => $data['mobile'],
         'role' => $data['role'],
         'password' => Hash::make($data['password']),                    
      ]);     
}

另一种方式是:

 User::find($user_id)->fill([
    'name' => $data['name'],
    'lastname' => $data['lastname'],
    'email' => $data['email'],
    'mobile' => $data['mobile'],
    'role' => $data['role'],
    'password' => Hash::make($data['password']),                    
 ])->save();

第一种方法可以在单个查询中进行更新,因此速度更快,但是第二种方法将触发模型事件,例如savingupdating,因此请选择所需的内容。

答案 1 :(得分:0)

您可以尝试:

$user= User::firstOrCreate(
['unique_field_name' => 'value'], 
['name' => $data['name'],
'lastname' => $data['lastname']]

);

唯一字段名称,例如电子邮件或用户ID或手机号码,它们是数据库中的唯一字段

答案 2 :(得分:0)

User::updateOrCreate(array('user_id' => $user_id), [
    'name' => $data['name'],
    'lastname' => $data['lastname'],
    'email' => $data['email'],
    'mobile' => $data['mobile'],
    'role' => $data['role'],
    'password' => Hash::make($data['password']),    
]);