Skip to content

Instantly share code, notes, and snippets.

@JacobBennett
Last active January 12, 2021 04:41
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JacobBennett/6b4bcdd859a2fc4401a2 to your computer and use it in GitHub Desktop.
Save JacobBennett/6b4bcdd859a2fc4401a2 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 = [];
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 = [
'fieldNameToValidate' => 'columnexists:table_name_to_check'
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment