如何解决未定义的变量,但它已经被声明为 Laravel
我的网站出现了一些问题。
最近,我一直在研究一个“过滤页面”,用户可以在其中选择/写入一个字符,然后使用该字符(从 A-Z 和 0-9)搜索 X 数据。字符可以是可选的。
这是我的 getAffiliates 函数:
public static function getAffiliates($community_id,$character) {
if (!empty($character)) {
$character = strval($character);
if (is_numeric($character)) {
$users = UserCommunity::with('user')->where('community_id',$community_id)->whereHas('user',function($q) {
$q->where('name','regexp','^[0-9]+');
})->get();
} else {
$users = UserCommunity::with('user')->where('community_id','like',$character.'%');
})->get();
}
} else {
$users = UserCommunity::with('user')->where('community_id',$community_id)->take(50)->get();
}
return $users;
}
这段代码的作用是,给定 X $community_id 和 X $character,它将确定 $character 是否为整数或不。然后,它将对数据库进行查询,并检索以给定参数为条件的集合。基本上,查询查找初始字符等于我的 $character 参数的值。
我不知道的是,为什么我会收到“未定义变量 $character”错误?
我的控制器代码是这样的(注意参数可以为空):
谁能解释一下到底哪里出了问题?
带有完整跟踪错误的更新
解决方法
你必须使用变量 top of where has 函数。访问它。
public static function getAffiliates($community_id,$character) {
if (!empty($character)) {
$character = strval($character);
if (is_numeric($character)) {
$users = UserCommunity::with('user')->where('community_id',$community_id)->whereHas('user',function($q) {
$q->where('name','regexp','^[0-9]+');
})->get();
} else {
$users = UserCommunity::with('user')->where('community_id',function($q) use ($character) {
$q->where('name','like',$character.'%');
})->get();
}
} else {
$users = UserCommunity::with('user')->where('community_id',$community_id)->take(50)->get();
}
return $users;
}
,
您的 $character
变量定义在其使用范围之外。
您可以使用 use
关键字将变量带入闭包的作用域,如下所示:
$users = UserCommunity::with('user')->where('community_id',$community_id)
->whereHas('user',function($q) use($character) { // <-- do this
$q->where('name',$character.'%');
})->get();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。