重定向返回错误并在自定义请求类中输入:Laravel 5

时间:2016-01-04 19:15:39

标签: php laravel-5 laravel-5.1

我有一些原始代码,如下所示,在MySQL数据库中使用表单验证和保存过程。

原始代码

public function store(Request $request)
{
    $v = \Validator::make($request->all(), [
        'Category' => 'required|unique:tblcategory|max:25|min:5'
    ]);

    if ($v->fails()) {
        return \Redirect::back()
                    ->withErrors($v)
                    ->withInput();
    }
    ...
    //code to save the record in database is here....
    ...
}

Then I followed this article 并修改了上述功能,现在看起来如下所示。

public function store(CategoryRequest $request)
{

    ...
    //code to save the record in database is here....
    ...
}

及以下是请求类

class CategoryRequest extends Request
{
    protected $redirect = \Redirect::back()->withErrors($v)->withInput();
    public function authorize()
    {
        return false;
    }
    public function rules()
    {
        return [
            'Category' => 'required|unique:tblcategory|max:25|min:5'
        ];
    }
}

错误详情

  

语法错误,意外'(',期待','或';'

此错误发生在以下行。

protected $redirect = \Redirect::back()->withErrors($v)->withInput();

我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

有多种方法可以告诉Laravel在验证失败时该怎么做。一种方法是覆盖response()方法并设置自己的响应,如下所示......

class CategoryRequest extends Request
{
    public function response(array $errors){
        return \Redirect::back()->withErrors($errors)->withInput();
    }

    public function authorize()
    {
        return false;
    }

    public function rules()
    {
        return [
            'Category' => 'required|unique:tblcategory|max:25|min:5'
        ];
    }
}

Laravel的默认响应是将您重定向到包含错误和输入值的上一页,因此在您的情况下可能不需要上述代码。

答案 1 :(得分:0)

在 Laravel 8 中,上述内容发生了变化,因此 response 函数对我不起作用,而另一方面 getRedirectUrl 起作用。这是一个代码片段

protected function getRedirectUrl()
{
    $url = $this->redirector->getUrlGenerator();
    return $url->previous();
}