Laravel 5.6 API响应中的验证错误

时间:2019-05-02 16:20:39

标签: laravel api laravel-5

我想通过api存储数据。它正在工作,但问题是,当我添加验证时,它没有给我相应的消息。我该如何解决?预先感谢

这是我的路线

Route::post('api/add_user', 'TestApiController@store'); 

这是我的控制人

public function store(Request $request)
{

    $validation = Validator::make(Request::all(), [
        'name' => 'required',
        'phone' => 'required',
        'email' => 'required'
    ]);


    if ($validation->errors()) {
        return $errors->toJson();
    } else {
        $testApi = new testApi();


        $testApi->name = $request->name;
        $testApi->phone = $request->phone;
        $testApi->email = $request->email;

        $testApi->save();


        return "ok";
    }

}

2 个答案:

答案 0 :(得分:1)

处理您的方法应如下所示:

 public function store(Request $request)
    {


$validator = Validator::make($request->all(), [
            'name' => 'required',
            'phone' => 'required',
            'email2' => 'required|email'
        ]);

 if($validator->fails()){
            // here we return all the errors message
            return response()->json(['errors' => $validator->errors()], 422);
        }


        $testApi = new testApi();

        $testApi->name = $request->name;
        $testApi->phone = $request->phone;
        $testApi->email = $request->email;

        $testApi->save();

       // 201 http code means that the server has proceced your request correctly
        return response()->json([], 201);
    }

答案 1 :(得分:0)

您不必手动执行此操作。简单地

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'phone' => 'required',
        'email' => 'required'
    ]);

    $testApi = new testApi();

    $testApi->name = $request->name;
    $testApi->phone = $request->phone;
    $testApi->email = $request->email;

    $testApi->save();

    return "ok";
}

这将自动处理验证,并在无效时返回错误消息。

更新

如果您想坚持使用自己的方法。这是您需要更改的地方。

if ($validation->fails()) {
    return $validation->errors();
}