Laravel 5:就地验证编辑 [英] Laravel 5: Validating Edits In-Place

查看:99
本文介绍了Laravel 5:就地验证编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前在此处问过一个问题用于使用Laravel 5和AJAX设置就地编辑.我之所以没有更新,是因为我已经离线进行管理以找出问题所在.

I had previously asked a question here in regards for setting up in-place editing with Laravel 5 and AJAX. I hadn't updated it because I had managed offline to figure out what was wrong with it.

尽管该表能够在适当位置编辑用户行,但我现在正尝试在该表的顶部添加验证,以期利用Laravel的内置验证器.但是,由于某种原因,它似乎无法正常工作.当我尝试通过JSON传递失败的验证器时,它会吐出我正在检查的每个可能的错误.好像验证程序将每个输入都视为空,这没有任何意义,因为该函数的其余部分显然是按预期接收输入的.

While the table is capable of editing user rows in-place, I'm now trying to add validation on top of it, intending on utilizing Laravel's built-in validator. However, for some reason it doesn't seem to be working. When I try to pass in the failed validator back through the JSON, it spits out every possible error I'm checking for. It's as if the validator is treating every input as empty, which doesn't make sense, as the rest of the function is clearly taking in the inputs as intended.

我上一个问题中的代码片段仍是最相关的,但是对 HomeController.php 进行了更新,如下所示:

The code snippets in my previous question are still mostly relevant, but there have been updates to HomeController.php, as can be seen below:

public function updateTable(Users $users){

    $user = request()->input('user');

    $first_name = request()->input('first_name');
    $last_name = request()->input('last_name');

    $validator = Validator::make(request()->all(), [
      'firstName'                     => 'required|alpha',
      'lastName'                      => 'required|alpha'
    ], [
      'firstName.required'            => 'You need to give a first name!',
      'firstName.alpha'               => 'A first name can only contain letters!',
      'lastName.required'             => 'You need to give a last name!',
      'lastName.alpha'                => 'A last name can only contain letters!'
    ]);

    if ($validator->fails()) {

      return response()->json($validator, 404);

    }

    $employees->editUser($user, $first_name, $last_name);

    return response()->json($user);

}

推荐答案

所以我意识到问题是双重的.首先,验证器失败时我试图返回的内容不正确.除了简单地传递整个验证程序外,我还需要简单地传递其消息,就像这样:

So I realized the issue was twofold. First, what I was trying to return when the validator failed was incorrect. Rather than simply passing the whole validator, I needed to simply pass its messages, like so:

if ($validator->fails()) {

  return response()->json($validator->messages(), 404);

}

第二个问题实际上与调用"request()-> all()"有关.我以为获得的数组可以工作,但是由于某种原因却没有.当我基于"request()"中的值创建一个新数组时,它能够获得我期望的验证器结果.

The second issue actually had to do with calling "request()->all()". I had assumed the array obtained would have worked, but for some reason it didn't. When I created a new array based on the values in "request()" it was able to get the validator results I was expecting.

这篇关于Laravel 5:就地验证编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆