Laravel 5.3验证问题

时间:2017-01-05 06:15:39

标签: laravel laravel-5.3

最近我从Laravel 5.3升级了Laravel 5.2,之后我发现了几个验证问题。其中一个奇怪的问题是规则required_without,即与laravel 5.2一起正常工作。

route是:

Route::post('chats/create','ChatController@insertMessage');

在内部控制器中,我已将方法insertMessage()定义为:

public function insertMessage(Request $request){
    $error = false; 
    $result = array();
    $responsecode = 200;
    $input = $request->all(); 

    $validator = Validator::make(
                    array(
                        "patient_id" => $input["patient_id"],
                        "chat_id" => !empty($input["chat_id"]) ? $input["chat_id"] : null, 
                        "sender_id"=> $input["sender_id"], 
                        "image" => $request->hasFile('file') ? $request->file('file') : null,
                        "content" => !empty($input["content"]) ? $input["content"] : null
                    ),
                    array(
                        "patient_id" => "required|exists:users,id,user_type,patient", 
                        "chat_id" => "sometimes|nullable|exists:chats,id", 
                        "sender_id"=>"required|exists:users,id", 
                        "image" => "required_without:content|image",
                        "content" => "required_without:image"
                    )
                );

    if ($validator->passes()){
        try {
            DB::beginTransaction();
            //Some operations

        }
        catch(\Exception $e){
            //Some operations
        }
    }
    //Finally return the response
    return response()->json(array(
        'error' => $error,
        'input_data' => $result),
        $responsecode
    );
}

我使用post-man制作的请求如下:

enter image description here

请求标头为Authorization,并且custom header,没有content-type标头。我得到的response是:

{
  "error": true,
  "input_data": {
    "error_message": "The image must be an image. "
  }
}

如果content数据中存在request字段,为什么需要图片?

使用语句dd($input);我可以将帖子数据作为:

array:4 [
  "patient_id" => "3"
  "content" => "Hello"
  "sender_id" => "1"
  "sender_name" => "System Admin"
]

1 个答案:

答案 0 :(得分:1)

您可以将验证规则用作

laravel 5.3

由于nullable具有image规则,您可以将其设置为输入值为空的位置。查看您的代码,如果请求中没有,则将contentnull设置为"image" => $request->hasFile('file') ? $request->file('file') : null, "content" => !empty($input["content"]) ? $input["content"] : null

validator

最后你的$validator = Validator::make( array( "patient_id" => $input["patient_id"], "chat_id" => !empty($input["chat_id"]) ? $input["chat_id"] : null, "sender_id"=> $input["sender_id"], "image" => $request->hasFile('file') ? $request->file('file') : null, "content" => !empty($input["content"]) ? $input["content"] : null ), array( "patient_id" => "required|exists:users,id,user_type,patient", "chat_id" => "sometimes|nullable|exists:chats,id", "sender_id"=>"required|exists:users,id", "image" => "nullable|required_without:content|image", "content" => "nullable|required_without:image" ) ); 应该是这样的,

Loader lm;

lm = new loader(ctx, feeList);

希望这会有所帮助!!