Last active
December 18, 2015 01:39
-
-
Save amodef/5705553 to your computer and use it in GitHub Desktop.
Laravel 4 validation with updated password and email fixes (on update, empty passwords are not taken into account and actual email is not considered as already taken).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BaseModel extends Eloquent { | |
public $errors; | |
public function validate($input = null) | |
{ | |
if (is_null($input)) $input = Input::all(); | |
$v = Validator::make($input, static::$rules); | |
if ($v->passes()) return true; | |
$this->errors = $v->messages(); | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// (...) | |
class User extends \BaseModel implements UserInterface, RemindableInterface { | |
// (...) | |
protected static $rules = [ | |
'email' => "required|email|unique:users", | |
'password' => 'required|confirmed|min:8' | |
]; | |
// Extend the validate function to take care of the 'update' specifities | |
public function validate($input = null) | |
{ | |
if (Input::get('_method') == 'PUT') | |
{ | |
// Ignore values on record with same id, and allow empty password | |
self::$rules['email'] .= ",email,$this->id"; | |
self::$rules['password'] = 'confirmed|min:8'; | |
// Ignore password validation if empty | |
if(!Input::get('password') and !Input::get('password_confirmation')) | |
{ | |
unset(self::$rules['password']); | |
unset(self::$rules['password_confirmation']); | |
} | |
return parent::validate(); | |
} | |
} | |
// (...) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class UsersController extends \BaseController { | |
// (...) | |
public function update($id) | |
{ | |
$user = User::find($id); | |
if (!$user) return Redirect::route('users.index'); | |
if ($user->validate()) | |
{ | |
$user->fill(Input::all()); | |
if(Input::get('password') and Input::get('password_confirmation')) $user->password = Hash::make(Input::get('password')); | |
if ($user->save()) return Redirect::route('users.index'); | |
} | |
return Redirect::back()->withErrors($user->errors); | |
} | |
// (...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment