Wednesday, November 9, 2016

Laravel validation trouble shootings

Laravel validation trouble shootings


While working on a project I stumbled upon this huge pile of problem of validating a form. Even though the fancy coding styles did make some things easy, it made some other things hard, especially when not having a complete documentation. So, heres a note for future.
1. Custom validation messages: Custom messages, if not in a language file must be written for each field and each of the rules of that field. So you cannot escape with a single message written for email field if you want it to be shown on every rule. You have to write that same message for each rule, individually
2. Field name renaming: When printing validation messages Laravel, if not instructed otherwise, will use a slightly polished version of the name attributes of you fields. So, for example name=user_name will be made into user name. So if you instead want it to look like "Username", you have to use the method called

setAttributeNames
Like this:

$attributeNames = array(
name => Name,
cat => Category,
);
$validator = Validator::make ( Input::all (), $rules );
$validator->setAttributeNames($attributeNames);
// Credits for: http://stackoverflow.com/a/25189223/1928610
3. Check uniqueness in a table having a different name than field name: Now what if you want to ensure that the user always enters an email that is not yet present in the users table when signing up. Laravel has a great validation rule for it called unique:table_name. So you use it like

email => unique:users
But if you are like me, you may at first run into the problem where your field name attribute does not match with the uniqueness field in your database. Like in my case, email fields name attribute contained email_address but in my users table, the column name was email. So to fix this, Laravel validaton just takes another attribute with the validator.

email_address => unique:users,email
Neat right?
Scouring through the documentation will help you more as it is doing for me. Ill keep posting further troubles I shoot in Laravel. InshaAllah.

Go to link download