यहाँ एक तरह से मैं इसे थोड़ी देर के लिए शोध करने के बाद कर रहा हूँ। मैं एक लारवल एपीआई एंडपॉइंट बनाना चाहता था जो यह जांचता है कि क्या कोई फ़ील्ड "उपयोग में है", इसलिए महत्वपूर्ण जानकारी है: 1) डीबी टेबल? 2) क्या DB कॉलम? और 3) क्या उस कॉलम में कोई मान है जो खोज शब्दों से मेल खाता है?
यह जानकर, हम अपने सहयोगी सरणी का निर्माण कर सकते हैं:
$SEARCHABLE_TABLE_COLUMNS = [
'users' => [ 'email' ],
];
फिर, हम अपने मान सेट कर सकते हैं जिन्हें हम जाँचेंगे:
$table = 'users';
$column = 'email';
$value = 'alice@bob.com';
फिर, हम प्रत्येक array_key_exists()और in_array()एक अभिभावक के साथ एक, दो कदम के कॉम्बो का उपयोग कर सकते हैं और फिर truthyशर्त पर कार्य कर सकते हैं:
// 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);
मैं लारवेल-विशिष्ट PHP कोड के लिए माफी माँगता हूँ, लेकिन मैं इसे छोड़ दूँगा क्योंकि मुझे लगता है कि आप इसे छद्म कोड के रूप में पढ़ सकते हैं। महत्वपूर्ण हिस्सा दो ifबयान हैं जिन्हें समान रूप से निष्पादित किया जाता है।
array_key_exists()और in_array()PHP फ़ंक्शन हैं।
स्रोत:
एल्गोरिथ्म कि मैं ऊपर से पता चला है के बारे में अच्छी बात यह है कि आप इस तरह के रूप में एक REST एंडपॉइंट कर सकते हैं GET /in-use/{table}/{column}/{value}(जहां table, columnहै, और valueचर हैं)।
आप ऐसा कर सकते थे:
$SEARCHABLE_TABLE_COLUMNS = [
'accounts' => [ 'account_name', 'phone', 'business_email' ],
'users' => [ 'email' ],
];
और फिर आप जैसे अनुरोध प्राप्त कर सकते हैं:
GET /in-use/accounts/account_name/Bob's Drywall (आपको पिछले भाग को एनोड करने की आवश्यकता हो सकती है, लेकिन आमतौर पर नहीं)
GET /in-use/accounts/phone/888-555-1337
GET /in-use/users/email/alice@bob.com
यह भी ध्यान दें कि कोई भी ऐसा नहीं कर सकता है:
GET /in-use/users/password/dogmeat1337क्योंकि passwordआपके लिए स्वीकृत कॉलम की सूची में सूचीबद्ध नहीं है user।
आपको यात्रा की शुभकामनाएं।