Coming from a Rails background for an MVC framework, one of the most common things to look for is a validation method for most of your inputs to avoid problems with your data later on. A good example is a uniqueness validation commonly used on usernames and email addresses.

In ROR, we can simply add the command for uniqueness in the model by this:
validate_uniqueness_of :username
automatically, this will apply validation for uniqueness every time a record is being saved.

While in Laravel, we can use a two-dimensional array to create a variable and then pass it to the Validator class for checking.
public static $rules = [
 'username' => 'unique:users'
$validation = Validator::make($data, static::$rules);

The Problem with Requirements -- additional fields

The codes above will only work if and only if you are just validating one column. But what if you are required to use two (or more) fields?

For rails we can simply write this as:
validate_uniqueness_of :username, :scope => [:column1, :column2]

Now for Laravel, a documentation is provided in their website for the validation. On the part under Adding Additional Where Clauses, it says that you can use additional conditions by adding parameters on the previous one. An example shown as this is also provided:
'email' => 'unique:users,email_address,NULL,id,account_id,1'

My issue with the documentation is that it doesn't necessarily says what the code does nor what each parameters does or are for. So...

Slicing the Parameters

Referencing on the code above and testing it through trial and error here is what I have found out.

The line of code above would actually result to an SQL command like this:
select count(*) as aggregate from `users` where `email` = 'EMAIL@ADDRESS' and `id` = NULL and `account_id` = 1;

To slice it (NOTE that I'm just trying to write what I have observed):
'email' => 'unique:users,email_address,
The default validation. The left side of the equation tells the column to check, followed the validation (in this case is uniqueness), then by the table and the field variable.
Next is the odd part of the code (IMO). The first parameter here is a value followed by the second column to check. The next part explains why I find it weird.
Compared to the previous part, here, the parameters interchanged in position being the field name first followed by the value. If ever there would be more values to check, the next pair would follow this format.

For whatever reason why the value interchanged, I am not yet sure. Though, combining this, we can say that the statement can go like this:

[field1] => '[validation]:[database],[var1],[var2],[field2],[field3],[var3],[fieldN],[varN]'

As you can see, you can add as many fields in the end for additional scoping of validation.

No comments :

Post a Comment