One approach is to create a validation function in the model and call it using the controller passing in the input, script and id (to ignore).
public function validate($input, $scenario, $id = null) { $rules = []; switch($scenario) { case 'store': $rules = [ 'name' => 'required|min:5|unique:users', 'email' => 'required|email|unique:users', 'password' => 'required|min:4|confirmed' ]; break; case 'update'; $rules = [ 'name' => 'required|min:5|unique:users' .',name,' . $id, 'email' => 'required|email|unique:users' .',email,' . $id, 'password' => 'min:4|confirmed' ]; break; } return Validator::make($input, $rules); }
Then in the controller:
$input = Input::all(); $validation = $user->validate($input, 'update', $user->id); if ($validation->fails()) {
As already mentioned, the third parameter of the unique rule specifies the id to ignore. You can add other cases, such as "login", to reuse the verification function.
Alternatively, Jeffrey Way at Tuts Premium has an excellent series of tutorials in βWhat New In Laravel 4,β which includes several other approaches for handling validation using services and listeners.
source share