laravel 在数组上调用成员函数 failed()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55910564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:19:50  来源:igfitidea点击:

Call to a member function fails() on array

phplaravel

提问by Luiiiz

I have a problem with the laravel validation.

我的 Laravel 验证有问题。

Call to a member function fails() on array

Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Call to a member function fails() on array"

Stacktrace:

`#0 Symfony\Component\Debug\Exception\FatalThrowableError in C:\laragon\www\frontine\app\Http\Controllers\authController.php:37

在数组上调用成员函数 failed()

Symfony\Component\Debug\Exception\FatalThrowableError 抛出消息“调用成员函数失败()在数组上”

堆栈跟踪:

`#0 Symfony\Component\Debug\Exception\FatalThrowableError in C:\laragon\www\frontine\app\Http\Controllers\authController.php:37

public function postRegister(Request $request)
{
    $query = $this->validate($request, [
        'user' => 'string|required|unique:users|min:4|max:24',
        'email' => 'email|string|required|unique:users',
        'pass' => 'string|required|min:8',
        'cpass' => 'string|required|min:8|same:pass',
        'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
    ]);

    if ($query->fails())
    {
        return redirect('/registrar')
            ->withErrors($query)
            ->withInput();
    }
}

采纳答案by Kenny Horna

The error is because what the ->validate()method returns an arraywith the validated data when applied on the Requestclass. You, on the other hand, are using the ->fails()method, that is used when creating validators manually.

错误是因为该->validate()方法array在应用于Request类时返回带有经过验证的数据的内容。另一方面,您正在使用->fails()手动创建验证器时使用的方法。

From the documentation:

文档

Manually Creating Validators

If you do not want to use the validatemethod on the request, you may create a validator instance manually using the Validatorfacade. The makemethod on the facade generates a new validator instance:

use Validator; // <------
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [ // <---
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

手动创建验证器

如果您不想validate在请求上使用该方法,您可以使用ValidatorFacade手动创建一个验证器实例。在 make门面上的方法生成一个新的校验器实例:

use Validator; // <------
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [ // <---
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

The ->fails()is called in the response of the Validator::make([...])method that return a Validatorinstance. This class has the fails()method to be used when you try to handled the error response manually.

->fails()被称为在响应Validator::make([...])返回的方法Validator实例。fails()当您尝试手动处理错误响应时,此类具有要使用的方法。

On the other hand, if you use the validate()method on the $requestobject the result will be an array containing the validated data in case the validation passes, or it will handle the error and add the error details to your response to be displayed in your view for example:

另一方面,如果您validate()$request对象上使用该方法,则结果将是一个包含验证数据的数组,以防验证通过,或者它将处理错误并将错误详细信息添加到您的响应中以显示在您的视图中例子:

    public function store(Request $request)
    {
       $validatedData = $request->validate([
            'attribute' => 'your|rules',
        ]);

       // I passed!

     }

Laravel will handled the validation error automatically:

Laravel 会自动处理验证错误:

As you can see, we pass the desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

如您所见,我们将所需的验证规则传递给了 validate 方法。同样,如果验证失败,将自动生成正确的响应。如果验证通过,我们的控制器将继续正常执行。

回答by Niellles

What this error is telling you is that by doing $query->failsyou're calling a method fails()on something (i.e. $query) that's not an object, but an array. As stated in the documentation$this->validate()returns an array of errors.

这个错误告诉你的是,通过这样做,$query->fails你正在调用一个方法 fails()(即$query),它不是一个对象,而是一个数组。如文档中所述,$this->validate()返回一系列错误。

To me it looks like you've mixed a bit of the example code on validation hooksinto your code.

在我看来,您似乎在代码中混合了一些有关验证挂钩的示例代码。



If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, [...] -Laravel Docs

如果验证规则通过,您的代码将继续正常执行;但是,如果验证失败,则会抛出异常,并自动将正确的错误响应发送回用户。在传统 HTTP 请求的情况下,将生成重定向响应,[...] - Laravel Docs

The following code should do the trick. You then only have to display the errors in your view. You can read all about that, you guessed it, in... the docs.

以下代码应该可以解决问题。然后,您只需在视图中显示错误。您可以阅读所有相关内容,您猜对了,在...文档中

public function postRegister(Request $request)
{
    $query = $request->validate($request, [
        'user' => 'string|required|unique:users|min:4|max:24',
        'email' => 'email|string|required|unique:users',
        'pass' => 'string|required|min:8',
        'cpass' => 'string|required|min:8|same:pass',
        'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
    ]);
}