Laravel FormRequest使用postman请求抛出404

04-26 16:24 字数 6 阅读 250 已编辑

1.表单验证

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class BusinessApply extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required'
        ];
    }

    /**
     * 自定义提示文案
     * 
     * @return array|string[]
     */
    public function messages()
    {
        return [
            'name.required' => '名称不为空'
        ];
    }

    /**
     * 重写验证不通过的处理方法
     *
     * @param Validator $validator
     */
    public function failedValidation(Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'code' => 500,
            'msg' => $validator->errors()->first(),
            'data' => null
        ], 200)));
    }
}

2.控制器中使用

public function apply(BusinessApply $request)
 {
    return 111;
 }

3.使用postman发起请求,抛出404,解决方法是在header添加Accept: application/json
4.附上stack overflow的解答:https://stackoverflow.com/questions/54768535/my-custom-message-request-validator-not-work-laravel?r=SearchResults

0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论