Last active
January 12, 2021 04:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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