Here is the way I have been doing this after researching for some time. I wanted to create a Laravel API endpoint that checks if a field is used, so the important information is: 1) what is the database table? 2) which database column? and 3) is there a value in this column that matches the search terms?
Knowing this, we can build our associative array:
$SEARCHABLE_TABLE_COLUMNS = [ 'users' => [ 'email' ], ];
Then we can set our values, which we will check:
$table = 'users'; $column = 'email'; $value = 'alice@bob.com';
Then we can use array_key_exists() and in_array() with eachother to execute a one-, two-stage combo and then the truthy condition:
// step 1: check if 'users' exists as a key in '$SEARCHABLE_TABLE_COLUMNS' if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) { // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table] if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) { // if table and column are allowed, return Boolean if value already exists // this will either return the first matching record or null $exists = DB::table($table)->where($column, '=', $value)->first(); if ($exists) return response()->json([ 'in_use' => true ], 200); return response()->json([ 'in_use' => false ], 200); } // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table], // then we need to tell the user we can't proceed with their request return response()->json([ 'error' => 'Illegal column name: '.$column ], 400); } // if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS, // then we need to tell the user we can't proceed with their request return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudocode. The important part is two if that execute synchronously.
array_key_exists() and in_array() are PHP functions.
source:
The good thing about the algorithm I showed above is that you can create a REST endpoint such as GET/in-use/{table}/{column}/{value} (where table , column and value are variables )
You could have:
$SEARCHABLE_TABLE_COLUMNS = [ 'accounts' => [ 'account_name', 'phone', 'business_email' ], 'users' => [ 'email' ], ];
and then you can make GET requests, such as:
GET/in-use/accounts/account_name/Bob Drywall (you may need to encode uri the last part, but usually not)
GET/in-use/accounts/phone/888-555-1337
GET/in-use/users/email/alice@bob.com
Note that no one can do:
GET/in-use/users/password/dogmeat1337 because password not listed in the list of allowed columns for user .
Good luck on your journey.