未定义变量但已声明 Laravel

Undefined variable but it's already declared Laravel

我的网站出现了一些问题。

最近,我一直在开发一个“过滤页面”,其中用户 selects/writes 一个字符,然后搜索具有该字符的 X 数据(从 A-Z 和 0-9)。字符可以是可选的.

这是我的 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', $community_id)->whereHas('user', function($q) {
                $q->where('name', '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 function。访问它。

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', $community_id)->whereHas('user', 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', 'like', $character.'%');
      })->get();