在验证循环值时遇到问题。 我从循环中获取值“mobile_no”和“email”,以验证这些值是否存在于我的其他表中,其中包含“手机号码”和“电子邮件”列。 感谢您的帮助。
$get_values = DB::table('users_preview')->get();
foreach($get_values as $values){
$email = $values->email;
$mobile_no = $values->email;
/* now I want to validate if values of email and mobile no exist in
user's table , this is my sample way to do it which is actually
wrong*/
// it only shows one validations but i like to show every each validations
for rows
if (users_preview::where('mobile', '=', $mobile_no)->count() > 0) {
return response()->json([
'message' => 'mobile is already
exist',
'errors' => $numbers,
'status' => false
]);
}
}
//scripts are
<script>
if(data.status == false){
//some codes
}
</script>
最佳答案
首先,在每个请求上查询所有行并不是一个好主意。试想一下,如果将来 yout 表中有数千行,您将达到默认为 30 秒的最大执行时间。
其次,这不是有效的 PHP 代码 - 只需查看行
和 undefined variable $numbers
。
第三,返回语句结束脚本执行。如果您想获取所有现有值,您可能应该返回循环之外。
接下来,您将查询表users_preview
中的所有记录 - 然后您将对照同一个表进行检查,假设users_preview
与您的 Eloquent 模型相同?
如果您尝试检查整个表中的重复项,请参阅 Stackoverflow 上的此问题:Finding duplicate values in a SQL table
例如,在 Laravel 中,您可以使用 users_preview::raw("- MY STATMENT - ")->get();
来执行原始语句。
另外 users_preview::where('mobile', '=', $mobile_no)->count();
可能是您的一个可能的解决方案。
希望有帮助。
关于javascript - Laravel 验证表中的唯一值以放入错误函数(js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799172/