大家好~
今天来认识如何自定义错误讯息且不用另外建立 FormRequest class 的方式吧~
Validator::make()
可以接受四个参数,
依序是:
$rules=[
'title' => 'required|string|max:50',
'content' => 'required|string|between:2,255'
];
$messages = [
'required' => ':attribute 未填。',
'string' => ':attribute 格式不支援。',
'between' => ':attribute 文字长度请在:min至:max间。',
'title.max' => ':attribute 文字长度请在:max以内。',
];
Validator::make($request->all(), $rules, $messages)->validate();
将我们定义好的参数依序放入即可~
以 Day05 我们完成的新增留言功能为例,
完整程序看起来会像这样:
public function store(Request $request)
{
$rules=[
'title' => 'required|string|max:50',
'content' => 'required|string|between:2,255'
];
$messages = [
'required' => ':attribute 未填。',
'string' => ':attribute 格式不支援。',
'between' => ':attribute 文字长度请在:min至:max间。',
'title.max' => ':attribute 文字长度请在:max以内。',
];
$validated = Validator::make($request->all(), $rules, $messages)->validate();
$message = Auth::user()->messages()->create($validated);
return response(MessageResource::make($message), Response::HTTP_CREATED);
}
然後来测试看看吧~
下图就是刚刚我们自定义的错误讯息喔!
Validator::make()
。那麽关於 Validation 的部分差不多就这样啦~
今天差不多先这样啦!
大家明天见啦~
若文章有任何问题,
还请大家不吝赐教!
>>: Day 12 :阵列(array)与链结串列(linked list)
没想到自己撑过了 30 天... 写到一半的时候,旅游不能病大发作 跑去大买一笔才缓解了自己的病症...
客户:我的需求不多,就一点点... 设计师:(已预知接下来无穷尽的...浩瀚宇宙) 多人可同时协同设...
来轻松聊聊 学会如何利用HTML编辑网页架构後,再来要进入让网页美化的CSS了。还不知道什麽是HTM...
1.首先先去工具->NuGet套件管理员->管理方案NuGet套件->安装Swas...
昨天在研究MDS的时候顺便把PCA也复习了一下,所以今天来把它相关的原理补上(非常推荐观看refer...