如何在laravel 5.4中进行服务器端api验证

时间:2017-06-22 11:28:48

标签: api laravel-5.4

如何以json格式向laravel 5.4中的邮递员发送发送错误消息

 //Controller
 public function store(Request $request)
 {
     $validator = Validator::make($request->all(),[
        'department_name'  => 'required',
     ]);
     if($validator->fails())
     {
        return $validator->errors()->all();
     }
     Department::create($request->all());

     return Response::json(['message' => 'Added','status' => 201],201);
}

1 个答案:

答案 0 :(得分:2)

您只需将验证错误作为json响应返回,如下所示:

if ($validator->fails()) { 
    return response()->json(['errors'=>$validator->errors()]); 
}