Skip to content

Instantly share code, notes, and snippets.

@atefBB
Forked from JacobBennett/Validation.php
Last active May 10, 2018 14:35
Show Gist options
  • Save atefBB/3b711dd9688e91cd983915fc97b69149 to your computer and use it in GitHub Desktop.
Save atefBB/3b711dd9688e91cd983915fc97b69149 to your computer and use it in GitHub Desktop.
Laravel Custom Validation to check if the given value Exists as a Column in Table
<?php
// BELIEVE THIS ONLY WORKS WHEN USING MYSQL
// DROP THIS INTO GLOBAL.PHP
Validator::extend('columnexists', function($attribute, $value, $parameters)
{
$query = DB::select("SHOW COLUMNS FROM " . $parameters[0]);
$columns = array();
foreach ($query as $column) {
array_push($columns, $column->Field);
}
if(in_array($value, $columns)) return true;
return false;
});
//IN YOUR RULES FOR YOUR VALIDATOR, USE AS FOLLOWS
$rules = array(
'fieldNameToValidate' => 'columnexists:table_name_to_check'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment