提交后的Ajax格式-Laravel



我正在做这个项目,我遇到了一些问题

如果我填写了所有字段,然后提交,就没有问题,并将其保存到数据库中,但我的问题是,如果某个字段为空,则验证消息错误将以JSON格式显示在另一个页面中。

我的视图文件中没有使用任何AJAX代码。

这是控制器代码:

public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');

这里是RegisterRequest代码:

public function rules()
{
return [
'name'         => 'required',
'email'        => 'required|email|unique:users,email',
'password'     => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];

你能帮我吗?

您的错误应该可以在带有$errors变量的刀片文件中访问,您需要迭代并显示错误。链接到文档,它将帮助您处理渲染部分-https://laravel.com/docs/7.x/validation#quick-显示验证错误

从文档和中清楚地看到

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

https://laravel.com/docs/7.x/validation#creating-表单请求

还要按照以下方式重构代码,只运行一个查询来创建用户,而不是创建然后更新。

public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

相关内容

  • 没有找到相关文章

最新更新