php - 请求类的自定义验证规则不起作用 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 FruitRequest
then 这给了我用户在邮递员中传递的价值。我不知道为什么这个自定义请求类不起作用。我附上了屏幕截图。请帮忙....
解决方案
很久不使用邮递员了,我正在用我的代码进行测试
我正在使用这样的 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"],
}
推荐阅读
- php - 检查Unix时间戳是否在MySQL的当前月份内
- python-requests - 使用带参数的 requests.Response(...)
- java - Android Studio Room Persistence - 每个实体是否应该有一个单独的 DAO,这对存储库类有何影响?
- domain-driven-design - 事件溯源的副作用
- mips - 给定数组的 MIPS 打印值
- regex - 使用 sed 删除特定字符之间的字符
- python - python优化目标搜索算法
- ruby-on-rails - 更新前检查记录
- excel - 获取当前的填充颜色
- python - 使用 ElementTree 从文件夹中读取多个 xml 文件