Skip to content

Instantly share code, notes, and snippets.

@amodef
Last active December 18, 2015 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amodef/5705553 to your computer and use it in GitHub Desktop.
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).
<?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;
}
}
<?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();
}
}
// (...)
}
<?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