简体   繁体   English

REST API、Laravel、验证

[英]REST API, Laravel, Validation

I have a small question.我有一个小问题。 I create simple API using Laravel.我使用 Laravel 创建了简单的 API。 When I use validation and if it fails, I got a common message:当我使用验证并且如果它失败时,我收到一条常见消息:

{
"result": false,
"message": "The given data failed to pass validation.",
"details": []
}

But how can I get details about which field fails and why like that:但是我如何获得有关哪个字段失败以及为什么会这样的详细信息:

{  
   "result":false,
   "message":"The given data failed to pass validation.",
   "details":{  
      "email":[  
         "The email field is required."
      ],
      "password":[  
         "The password must be at least 3 characters."
      ]
   }
}

My code in controller looks like this:我在控制器中的代码如下所示:

protected function validator(array $data)
{
    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:3',
    ]);

    return $validator;
}

protected function create(array $data)
{

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'role_id' => 2
    ]);
}

It is better to handle the validator within the same process, like this:最好在同一进程中处理验证器,如下所示:

public function register(Request $request){
    $validator =  Validator::make($request->all(),[
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6|confirmed',
    ]);

    if($validator->fails()){
        return response()->json([
            "error" => 'validation_error',
            "message" => $validator->errors(),
        ], 422);
    }

    $request->merge(['password' => Hash::make($request->password)]);

    try{
        $user = User::create($request->all());
        return response()->json(['status','registered successfully'],200);
    }
    catch(Exception $e){
        return response()->json([
            "error" => "could_not_register",
            "message" => "Unable to register user"
        ], 400);
    }
}

You should make sure you're sending the request with the Accept: application/json header.您应该确保使用 Accept: application/json 标头发送请求。

Without that - Laravel won't detect that it's an API request,没有那个 - Laravel 不会检测到它是一个 API 请求,

If validation fails, a redirect response will be generated to send the user back to their previous location.如果验证失败,将生成重定向响应以将用户发送回他们之前的位置。 The errors will also be flashed to the session so they are available for display.错误也将闪现到会话中,以便它们可供显示。 If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.如果请求是 AJAX 请求,则会向用户返回带有 422 状态代码的 HTTP 响应,其中包括验证错误的 JSON 表示。

check the documentation 检查文档

I used validate in my project:我在我的项目中使用了验证:

1.I created app/http/requests/CreateUserRequestForm.php 1.我创建了 app/http/requests/CreateUserRequestForm.php

public function rules()
    {
        return [
            "name"       => 'required',
            "address"    => 'required',
            "phnumber"   => 'required|numeric',

        ];
    }

    public function messages()
    {
        return [
            'name.required'     => 'Please Enter Name',
            'addresss.required' => 'Please Enter Address',
            'phnumber.required' => 'Please Enter PhNumber'

        ];
    }
  1. call the RequestForm in controller在控制器中调用 RequestForm

use App\\Http\\Requests\\CreateUserRequestForm;使用 App\\Http\\Requests\\CreateUserRequestForm;

public function createUser(CreateUserRequestForm $request)
    {
        // create       
        $user= UserModel::create([
            'name'      => $request->input('name'),
            'address'   => $request->input('address'),
            'phnumber'  => $request->input('phnumber')

        ]);      

        return response()->json(['User' => $user]);
    }

Try this i didn't try but it should be work for you.试试这个我没试过,但它应该适合你。

You may use the withValidator method.您可以使用 withValidator 方法。 This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated.此方法接收完全构造的验证器,允许您在实际评估验证规则之前调用其任何方法。

take reference from here.从这里参考。 laravel validation Laravel 验证

/**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('email', 'Please enter valid email id');
            }
        });
    }

Try this:试试这个:

    public function create(){
     
       // ------ Validate -----
       $this->vallidate($request,[
             'enter code here`name' => 'required|string|max:255',
             'email' => 'required|string|email|max:255|unique:users',
             'password' => 'required|string|min:3'
       ]);

       // ------ Create user -----
       $user = User::create(['name' => $request->name']);

       return response()->json([
           'message' => "success",
           'data'    => $user``
       ]);
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM