/**
* Processes the form.
*
* @param string $mode
* @param int $id
* @return \Illuminate\Http\RedirectResponse
*/
protected function processForm($mode, $id = null)
{
$rules = ['email' => 'required|unique:users', 'password' => 'sometimes|required', 'password_confirm' => 'required_with:password|same:password'];
if ($id) {
$user = $this->users->createModel()->find($id);
$rules['email'] .= ",email,{$user->email},email";
$input = $this->prepareInput(Input::all(), $mode === 'update' ? true : false);
$messages = $this->validateUser($input, $rules);
if ($messages->isEmpty()) {
try {
// Update the user
$this->users->update($user, array_except($input, 'roles'));
// Get the new user roles
$roles = array_get($input, 'roles', []);
// Get the user roles
$userRoles = $user->roles->lists('id');
// Prepare the roles to be added and removed
$toAdd = array_diff($roles, $userRoles);
$toDel = array_diff($userRoles, $roles);
// Detach the user roles
if (!empty($toDel)) {
$user->roles()->detach($toDel);
}
// Attach the user roles
if (!empty($toAdd)) {
$user->roles()->attach($toAdd);
}
} catch (NotUniquePasswordException $e) {
return Redirect::back()->withInput()->withErrors('This password was used before. You must choose a unique password.');
}
}
} else {
$input = $this->prepareInput(Input::all(), true);
$messages = $this->validateUser($input, $rules);
if ($messages->isEmpty()) {
$user = $this->users->create($input);
$activation = Activation::create($user);
Activation::complete($user, $activation->code);
}
}
if ($messages->isEmpty()) {
return Redirect::route('users.index')->withSuccess(trans("users/messages.success.{$mode}"));
}
return Redirect::back()->withInput()->withErrors($messages);
}