So let's say I've got a custom request called CreateReviewRequest
.
In this request, I've got this method:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required_if(auth->logged)',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
As you can see in the name
key, I want from the client to be required to fill the name
field if he's not logged in.
So my question is, how can I exactly require my client to fill the name
when he's a guest?
You can use check()
method:
public function rules()
{
return [
'name' => auth()->check() ? 'required' : '',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
Can't you make a simple check?
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if (auth()->check()) {
return [
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
return [
'name' => 'required',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
Member only:
$validator = Validator::make($request->all(), [
'email' => auth()->check() ? '' : 'required|min:5|max:60|email',
]);
Guest only:
$validator = Validator::make($request->all(), [
'user_id' => auth()->check() ? 'required|integer|min:1' : '',
]);
Both:
$validator = Validator::make($request->all(), [
'message' => 'required|min:10|max:1000'
]);
Combined:
$validator = Validator::make($request->all(), [
'email' => auth()->check() ? '' : 'required|min:5|max:60|email',
'user_id' => auth()->check() ? 'required|integer|min:1' : '',
'message' => 'required|min:10|max:1000'
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.