代码之家  ›  专栏  ›  技术社区  ›  Jagdish Sharma

如何在laravel中检查请求变量内部的空数组?

  •  0
  • Jagdish Sharma  · 技术社区  · 7 年前

    代码:

    public function specificationsave(Request $request) {   
        if (!empty($request->product_id)) {
            if (empty($request->specificationkeys) && empty($request->specificationvalues)) {
                return response()->json(["message" => 'Empty form submitted'], 202);
            } else {
                // something code 
            }
        } else {
            return response()->json(["message" => 'something went wrong with product'], 403);
        }
    }
    

    表格代码:

    <input type="text" name="specificationkeys[]"/>
    <input type="text" name="specificationvalues[]"/>
    

    当我把空的条件放在我的 specificationkeys 数组它不起作用,因为我的密钥有一个空数组,所以我可以检查密钥是否有数组,或者我想在没有验证器的情况下进行空检查,因为字段不是必需的。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Jignesh Joisar    7 年前

    例如 product_id 返回为 array 像这样检查情况

    if($request->product_id && is_array($request->product_id) && count($request->product_id) > 0) {
         //success validation
    }else {
        //failed validation 
    }
    
        2
  •  1
  •   Amol Rokade    7 年前

     if (count($request->specificationkeys) == 0 && count($request->specificationvalues) == 0){
         //your logic for empty
      }else{
        //Your logic for not empty  
     } 
    
        3
  •  0
  •   Andreas Hunter    7 年前

    试试这个:

    public function specificationsave(Request $request) {   
        if (isset($request->product_id) && !empty($request->product_id)) {
            if (is_array($request->specificationkeys) && 
                count($request->specificationkeys) !== 0 && 
                is_array($request->specificationvalues) && 
                count($request->specificationvalues) !== 0) {
                return response()->json(["message" => 'Empty form submitted'], 202);
            } else {
                // something code 
            }
        } else {
            return response()->json(["message" => 'something went wrong with product'], 403);
        }
    }