0

下面的代码显示了错误(在行上if ($response) {):

未定义变量:响应

我正在检查if内部的条件,foreach因为我想检查表中的每个是否存在于id表中。也在显示数据的条件下。UserEnabledNotificationsnotificationsdump($response);ifforeach

我可以在循环$response外获取数据吗?foreach我应该尝试什么?

$notificationData = UserEnabledNotifications::all();

foreach ($notificationData->where('status', 'true') as $user => $value) {
    if (Notifications::where('userEnabledNotificationsId', $value['id'])->exists() == false) {
        $notificationTypeName = NotificationTypes::where('id', $value['notificationTypesId'])
            ->value('notificationTypeName');

        $userData = User::where('id', $value['userId'])
            ->get()
            ->toArray();

        $data = [];

        $data['notificationTypesId'] = $value['notificationTypesId'];
        $data['notificationTypeName'] = $notificationTypeName;
        $data['userId'] = $value['userId'];
        $data['email'] = $userData[0]['email'];
        $data['recipientName'] = $userData[0]['FullName'];
        $data['userEnabledNotificationsId'] = $value['id'];

        $response = Notifications::create($data);
        //dump($response);

        $tags[] = $response;
    }
}

if ($response) {
    return response()->json([
        'message' => 'success',
        'data' => $tags,
        'statusCode' => 200,
        'status' => 'success'
    ], 200);
}
4

3 回答 3

2

$response首先定义 if body 但您需要$response = null在此之上。

于 2021-08-31T06:48:11.490 回答
0

您可以创建一个私有或受保护的变量,并将其放在外面,然后直接或通过函数访问它

$notificationData = UserEnabledNotifications::all();
private $reponse = null;

foreach ($notificationData->where('status', 'true') as $user => $value) {

   if(Notifications::where('userEnabledNotificationsId',$value['id'])->exists()==false){
                      
      $notificationTypeName = NotificationTypes::where('id', $value['notificationTypesId'])->value('notificationTypeName');
      
      $userData = User::where('id', $value['userId'])->get()->toArray();
      
      $data = [];
      $data['notificationTypesId'] = $value['notificationTypesId'];
      $data['notificationTypeName'] = $notificationTypeName;
      $data['userId'] = $value['userId'];
      $data['email'] = $userData[0]['email'];
      $data['recipientName'] = $userData[0]['FullName'];
      $data['userEnabledNotificationsId'] = $value['id'];
      $response = Notifications::create($data);
      
      $tags[] =  $response;
    }      
  }  
  if ($response) {
          return response()->json([
                    'message' => 'success',
                    'data' => $tags,
                    'statusCode' => 200,
                    'status' => 'success'
                ], 200);
  }

但是现在每个地方都需要检查响应是否为空。

为什么是私有的、受保护的或公共的?

检查这个答案:公共、私有和受保护之间有什么区别?

我引用

  • 公共范围以使该属性/方法可在任何地方、其他类和对象的实例中使用。
  • 当您希望您的属性/方法仅在其自己的类中可见时,私有范围。
  • 当您想让您的属性/方法在所有扩展当前类(包括父类)的类中可见时,受保护范围。
于 2021-08-31T06:47:25.233 回答
0

只需null在变量中声明一个或一个空数组,$response您就可以将数据从循环中取出!

于 2021-08-31T10:30:33.750 回答