【问题标题】:Laravel API controller | How can i hash the password in this "update" method of the controller?Laravel API 控制器 |如何在控制器的这种“更新”方法中散列密码?
【发布时间】:2020-10-18 22:15:20
【问题描述】:

这是我的 API 控制器中的方法,它假定更新用户数据。其中一列是密码,假设在插入之前进行哈希处理。

public function update($id, Request $request)
{
    $user = $this->userRepository->findWithoutFail($id);
    
    if (empty($user)) {
        return $this->sendResponse([
            'error' => true,
            'code' => 404,
        ], 'User not found');
    }
    $input = $request->except(['api_token']);
    try {
        if ($request->has('device_token')) {
            $user = $this->userRepository->update($request->only('device_token'), $id);
        } else {
            $customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
           
            $user = $this->userRepository->update($input, $id);
            
            foreach (getCustomFieldsValues($customFields, $request) as $value) {
            
                $user->customFieldsValues()
                    ->updateOrCreate(['custom_field_id' => $value['custom_field_id']], $value);
            }
        }
    } catch (ValidatorException $e) {
        return $this->sendError($e->getMessage(), 401);
    }

    return $this->sendResponse($user, __('lang.updated_successfully', ['operator' => __('lang.user')]));
}

现在,在使用此方法更新用户数据时,密码的原始文本被插入到用户表中。我希望使用以下代码对其进行哈希处理。但我不知道在上面的方法中应该去哪里。有人可以帮忙吗??

 $user->password = Hash::make($request->input('password'));

将要更新的请求正文示例:

{"id":"147","name":"tipumon","email":"a@gmail.com","phone":"9898365627","useraddress":"test address","password":"passwordtext","api_token":"<apiTokenstring>","bio":"","media":{"id":null,"name":null,"url":"https://example.com/public/images/image_default.png","thumb":"https://example.com/public/images/image_default.png","icon":"https://example.com/public/images/image_default.png","formated_size":null}}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    自己解决了。

       public function update($id, Request $request)
        {
             
            $user = $this->userRepository->findWithoutFail($id);
            
            if (empty($user)) {
                return $this->sendResponse([
                    'error' => true,
                    'code' => 404,
                ], 'User not found');
            }
            $input = $request->except(['api_token']);
            $input['password'] = Hash::make($request->input('password'));
    

    【讨论】:

    • 为什么不让存储库来做呢?
    猜你喜欢
    • 2013-12-20
    • 1970-01-01
    • 2020-04-18
    • 2017-09-20
    • 2019-02-04
    • 2018-07-07
    • 2010-12-04
    • 2014-11-29
    • 1970-01-01
    相关资源
    最近更新 更多