Laravel - 当 return 使用 Redirect::to 时控制器没有设置一些变量

Laravel - Controller not setting some variables when return using Redirect::to

在我的控制器中,我验证了输入字段,如果任何验证失败,我想 return 返回到表单并重新填充用户输入的先前值(如果有任何其他更简单的方法)这个请告诉我)。但我正在做的是:

Controller.php:

public function store(Request $request, AnexoController $anexoController)
{
    $validator = Validator::make(
        $request->all(), 
        $rules, 
        $messages
    );

    if($validator->fails())
    {
        return Redirect::to($request->headers->get('referer'))
         ->withErrors($validator)
         ->withReq($request->all());
    }

    // continues the function...
}

在view.blade.php:

<input type="text" 
    maxlength="256" 
    id="text-input" 
    name="id" 
    placeholder="Código" 
    class="form-control" 
    @if(isset($req)) value="{{$req->id}}"
    @else value="$REQ VARIABLE NOT SET"
    @endif
    required>

当我测试它时,字段 id 的值被设置为“$REQ VARIABLE NOT SET”,但是 $errors from $validator 变量被设置。那么,为什么不在此上下文中设置变量 $req 呢?提前致谢。

使用这个

$request->validate([
  //rules
]);

它会自动 return 形成包含所有错误和输入的页面,

在您的表单中,您需要为旧输入的输入值添加一个助手

<input type="text" value={{ old('email')}} name="email">

https://laravel.com/docs/5.8/validation & https://laravel.com/docs/5.8/helpers