首页 > 解决方案 > 在 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>

标签: phplaravel

解决方案


你可以使用这个:

return Redirect::back()->withInput(Input::all());

如果你正在使用表单请求验证,这正是 Laravel 将如何通过错误和给定的输入将你重定向回来。

摘自\Illuminate\Foundation\Validation\ValidatesRequests

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

推荐阅读