简体   繁体   English

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

[英]Redirect back with errors and input in custom request class : Laravel 5

I had some original code that shows like below with form validation and saving process in MySQL Database.我有一些原始代码,如下所示,其中包含 MySQL 数据库中的表单验证和保存过程。

Original Code原始代码

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 and modified the above function and now it looks like below. 然后我按照这篇文章修改了上面的函数,现在看起来像下面这样。

public function store(CategoryRequest $request)
{

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

and below is the Request class下面是请求类

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'
        ];
    }
}

Error Details错误详情

syntax error, unexpected '(', expecting ',' or ';'语法错误,意外的 '(',期待 ',' 或 ';'

This error is coming at below line.此错误出现在以下行中。

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

Am I missing something ?我错过了什么吗?

There are multiple ways to tell Laravel what to do when validation fails.有多种方法可以告诉 Laravel 在验证失败时该做什么。 One method is to overwrite the response() method and set your own response as follows...一种方法是覆盖 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's default response is to redirect you to the previous page with errors and input values so the above code is probably not required in your case. Laravel 的默认响应是将您重定向到包含错误和输入值的上一页,因此在您的情况下可能不需要上述代码。

In Laravel 8 the above has changed, so the response function did not work for me, getRedirectUrl on the other hand did.在 Laravel 8 中,上述内容发生了变化,因此response函数对我getRedirectUrl ,另一方面, getRedirectUrl了。 Here's a code snippet这是一个代码片段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM