I read everywhere that in model validation is best practice, but I don't know how to handle a failed validation. Here are some rules (declared in Model User):
public static $rules = array (
'username' => 'required|between:4,16',
'email' => 'required|email',
'password' => 'required|alpha_num|min:8|confirmed',
'password_confirmation' => 'required|alpha_num|min:8'
);
When done like this, it will take a 'long' time before the validation occurs. Let's suppose the passwords don't match up and I eventually arrive at trying to save the data in the db like this:
$user->save();
save() will return false and the user won't get inserted into the db. I can't believe this is supposed to be best practice, how do I notify the user from this position what he did wrong? I don't even know what went wrong as the only feedback I get is true or false. I could make validators for each rule but that's just silly.
This same problem goes for the table definition conditions like:
$table->string('username')->unique();
If the username provided is not unique then Its very hard to give feedback to the user all the way in the view where he is located. I'm very new to Laravel and web development newb in general. How do you guys handle a simple log in validation?
The goal to achieve is to have controller actions that look like that (example a store action)
public function store(){
$input = Input::only('username', 'blahblah', ...);
$user = new User($input);
if(!$user->save()){
// Redirect to the form page with data and errors
return Redirect::route('users.create')
->withInput()
->withErrors($user->getErrors());
}
// Redirect to show with a success message
return Redirect::route('users.show', $user->id)
->with('notice', 'User successfully created');
}
You can see that your user model can perform validation on save and store the resulting error.
$validator = Validator::make(Input::all(), User::$rules)
if($validator->fails() {
return Redirect::back()->withInput()->withErrors($validator);
}
$user = User::create(Input::all);
You will have to set the protected $fillable = []; or protected $guarded = []; in User model
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community