首页 > 解决方案 > 请求类的自定义验证规则不起作用 laravel 7

问题描述

以下是我的代码;

FruitRequest.php

class FruitRequest extends Request
{

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' => 'required|alpha',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ];
}

public function messages()
{
    return ['name.required' => response("Name should be mandatory", 404),
        'name.alpha' => response("Name should be contains only letters", 404),
        'image.required' => response("Foto should be mandatory", 404),
        'image.mimes' => response('Foto should be jpeg,png,jpg,gif,svg', 404),
        'image.max' => response('Foto size should be blow 2 MB', 404),
    ];
}

}

FruitController.php

use App\Http\Controllers\Controller;
use App\Http\Requests\FruitRequest;

class FruitController extends Controller
{

public function store(FruitRequest $request)
{
    echo $request->input('name');

    //above line gives nothing to me
}

}

如果我使用extends Request而不是extends FruitRequestthen 这给了我用户在邮递员中传递的价值。我不知道为什么这个自定义请求类不起作用。我附上了屏幕截图。请帮忙....

在此处输入图像描述

标签: phplaravellaravel-7

解决方案


很久不使用邮递员了,我正在用我的代码进行测试

我正在使用这样的 FormRequest:

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

class YourRequest extends FormRequest
{
  //this function called if Validator::make()->fails();
  //here where you can modifying your message
  protected function failedValidation(Validator $validator)
  {
    //note this only for API, for formData use \Illuminate\Validation\ValidationException($validator)
    throw new HttpResponseException(response()->json($validator->errors()->all(), 422));
    //this will get parameter attribute set from FormRequest
    //attributes() along with the error message, 
    //or $validator->errors()->all() to get messages only like my screenshot
    //or modify message with your logic
  }

  public function authorize() { return true; }
  public function rules() { return []; }
  public function attributes() { return []; }
  public function messages() { return []; }
}

在控制器中:

use YourRequest;

public function store(YourRequest $req)
{
  return response($req->all())->setStatusCode(200); 
}

在您的 FormRequest 替换 response() 中,只需文本:

public function messages()
{
    return ['name.required' => "Name should be mandatory"],
}

2nd,验证alpha只接受字母,你的名字是数字,来自我的代码(我使用默认的验证器消息,它在消息数组中): 邮差


推荐阅读