php - 在 Laravel 中重定向后使用模型对象填充表单
问题描述
我有一个运行良好的模型的基本 CRUD 结构。现在我想重定向到 create 方法并使用预先存在的模型填充表单。它可以由用户选择一个 id 来工作,然后我会选择该模型并重定向到创建页面并填充表单。
这是我迄今为止尝试过的
$order = Orders::find($id);
$inventory = Inventory::where(['id' => $order->inventory_id])->first()->toArray();
return redirect()->route('backend.inventory.create', $inventory['bag_id'])->withInput($inventory);
在上面的示例中,它找到了订单并选择了与其相关的单个库存项目(我已经确认它肯定是按预期选择了一个库存项目)并重定向到库存创建页面。但是,当使用 ->withInput() 方法时,这似乎并没有像我预期的那样用数据填充我的表单。
如何使用重定向将数据传递到表单?
按以下要求添加表单代码。这只是表格的一列,因为它是一个巨大的代码块
<div class="form-group row" id="item-name" v-if="type != '3'">
<label for="name" class="col-md-2 col-form-label text-md-right">Item Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required>
@if ($errors->has('name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</div>
解决方案
你可以使用这个:
return Redirect::back()->withInput(Input::all());
如果你正在使用表单请求验证,这正是 Laravel 将如何通过错误和给定的输入将你重定向回来。
摘自\Illuminate\Foundation\Validation\ValidatesRequests:
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
推荐阅读
- websocket - 在不同的端口上收到响应
- sql - 如何在不丢失外键的情况下合并两个sqlite数据库?
- bash - 如何从所有其他行值中减去特定行值的值?
- html - 替换*没有*属性的所有元素
- ansible - Ansible 如何在命令行中指定组来运行相应的任务
- c++ - 为什么将“:/Icons/controller.png”给构造函数工作(这是有效的相对文件路径语法)?
- python - 多处理池不执行功能
- powershell - powershell中的计时器事件在远程会话中不起作用
- swift - 使用添加的 url 方案时,Urls 不会打开
- python - IntegrityError:数据类型不匹配