/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // set up validation rules for different fields that may be passed in $messages = ['value.required' => 'This field cannot be blank.', 'value.regex' => 'The username must be at least 3 alphanumeric characters long.', 'value.unique' => 'The ' . $request->input('name') . ' must be unique.', 'value.email' => 'This must be a valid email address.', 'value.mobile' => 'This must be a valid phone number.']; $rules = []; switch ($request->input('name')) { case 'first_name': case 'last_name': $rules = ['value' => ['required']]; break; case 'username': $rules = ['value' => ['required', 'unique:users,username', 'regex:/^[\\w]{3,}$/']]; break; case 'email': $rules = ['value' => ['required', 'email', 'unique:users,email']]; break; case 'mobile': $rules = ['value' => ['regex:/^\\(\\d{3}\\) \\d{3}-\\d{4}$/']]; default: // unknown field } // validate $this->validate($request, $rules, $messages); // find the user if ($user = User::findBySlugOrId($id)) { // update and save the field being edited $user->{$request->input('name')} = $request->input('value'); $user->save(); // return a JSON representation of the updated user return $user->toJson(); } return json_encode($request->input()); }
/** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create(['name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password'])]); }