laravel 更新


public function update(Request $request, ResponseFactoryContract $response)
    {
        $user = $request->user();
        $rules = [
            'name' => ['nullable', 'string', 'username', 'display_length:2,12'],
            'bio' => ['nullable', 'string'],
            'sex' => ['nullable', 'numeric', 'in:0,1,2'],
            'location' => ['nullable', 'string'],
            'avatar' => ['nullable', 'string', 'regex:/public:(.+)/is'],
            'bg' => ['nullable', 'string', 'regex:/public:(.+)/is'],
        ];
        $messages = [
            'name.string' => '用戶名只能是字符串',
            'name.username' => '用戶名只能以非特殊字符和數字開頭,不能包含特殊字符',
            'name.display_length' => '用戶名長度不合法',
            'bio.string' => '用戶簡介必須是字符串',
            'sex.numeric' => '發送的性別數據異常',
            'sex.in' => '發送的性別數據非法',
            'location.string' => '地區數據異常',
            'avatar.regex' => '頭像錯誤',
            'bg.regex' => '背景圖片錯誤',
        ];
        $this->validate($request, $rules, $messages);

        $target = ($name = $request->input('name'))
            ? $user->newQuery()->where('name', $name)->where('id', '!=', $user->id)->first()
            : null;
        if ($target) {
            return $response->json(['name' => ['用戶名已被使用']], 422);
        }
        $fields = ['name', 'bio', 'sex', 'location', 'avatar', 'bg','true_name','true_name_set','company','occupation','industry','birthday','school','hometown','tagss'];
        foreach ($fields as $field) {
            if ($request->request->has($field)) {
                $user->{$field} = $request->input($field);
            }
        }

        return $user->save()
            ? $response->make('', 204)
            : $response->json(['message' => ['更新失敗']], 500);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM