Laravel 7:使失败的验证响应200代替422

k97glaaz  于 2022-12-27  发布在  其他
关注(0)|答案(3)|浏览(159)

我正在创建一个Laravel 7应用程序。
我已经创建了一个POST API,它接受2个参数并添加了验证。当验证失败时,它会给出响应“422 unprocessable entity”,并给出如下JSON格式的错误:

{
    "message": "The given data was invalid.",
    "errors": {
        "mobile_no": [
            "The mobile no must be 10 digits."
        ]
    }
}

现在,我需要相同的响应,错误代码为200,而不是422。
我应该如何实现这一目标?

rseugnpd

rseugnpd1#

您可以使用错误处理程序来实现此目的。https://laravel.com/docs/7.x/errors#render-method

public function render($request, Exception $exception)
 {
     if ($condition)) {
       return response()->json($content, 200);
     }

    return parent::render($request, $exception);
}

检查所需的内部函数异常并将其替换为成功响应

2admgd59

2admgd592#

对于laravel 8,我覆盖了app/Exceptions/Handler.php中的方法invalidJson

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
        'message' => $exception->getMessage(),
        'errors' => $exception->errors(),
    ], 200); //parent method return 422
}
fzwojiic

fzwojiic3#

根据Laravel文档,第节"手动创建验证器“

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
 
class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);
 
        if ($validator->fails()) {
            // here add your 200 response
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }
 
        // Retrieve the validated input...
        $validated = $validator->validated();
 
        // Retrieve a portion of the validated input...
        $validated = $validator->safe()->only(['name', 'email']);
        $validated = $validator->safe()->except(['name', 'email']);
 
        // Store the blog post...
    }
}

相关问题