我使用的是PHP 7和Laravel 6。当我制定用户请求规则并在用户控制器中使用它时,我遇到了错误。我制定的请求规则是在创建和更新功能中可重复使用,所以如果我传递用户的id,它将验证除该id之外的用户的唯一性。但如果不是,它将搜索所有id并验证它是否唯一。我遵循BaM解决方案,在这里:https://stackoverflow.com/a/24205849
这是我的UserRequest.php:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users' . ($id ? ",$id" : ''),
'phone_number' => 'required|string|min:9|max:10|unique:users' . ($id ? ",$id" : ''),
'user_img' => 'required|mimes:jpeg,jpg,png,gif|max:10000',
],
$merge);
}
这是我的用户控制器:
public function store(Request $request)
{
$extend_rules = [
'pass' => 'required|string|min:8',
];
$validator = Validator::make($request->all(), UserRequest::rules($extend_rules));
if ($validator->fails())
{
return redirect()->back();
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->pass),
'phone_number' => $request->phone_number,
'user_img' => $request->user_image->store('user_img'),
]);
$user->save();
Session::flash('message', 'Your account is successfully created !');
Session::flash('alert-class', 'alert alert-success');
return redirect()->route('users.index');
}
我得到了这个错误:
ErrorException:数组到字符串转换
我试图寻找解决方案,但似乎找不到任何我的案例。
如果有人知道,请帮帮我!
这是因为您只是传递一个数组,而该方法接受两种不同类型的参数
$validator = Validator::make($request->all(), UserRequest::rules(0, $extend_rules)); // <-- you need to either pass 1 or 0 for the id and then $extended rules
// here is your method signature
public static function rules ($id=0, $merge=[]) {