【问题标题】:Is it possible to get keys from Laravel array-syntax inputs?是否可以从 Laravel 数组语法输入中获取键?
【发布时间】:2018-06-26 18:11:16
【问题描述】:

给定一个格式为:

<form method="POST" action="{{ route('post') }}">
{{ csrf_field() }}
@foreach([
    'firstname' => 'First name',
    'lastname' => 'Last name',
] as $key => $label)
    <label for="person[{{ $key }}]">{{ $label }}</label>
    <input name="person[{{ $key }}]" id="person[{{ $key }}]" type="text" />
@endforeach
<input type="submit" value="Send" />
</form>

还有一个模型:

use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    protected $fillable = [
        'firstname',
        'lastname',
    ];
}

我想使用 Laravel 的 Illuminate\Http\Request::input() 函数从表单中检索所有 person 字段并从中填充模型。

我用来测试此功能的示例路线是:

use Illuminate\Http\Request;
use App\Person;

Route::post('/testcase', function(Request $request) {
    $person = new Person;
    $fields = $request->input('person.*');
    $person->fill($fields);
    var_dump(
        $person->firstname,
        $person->lastname,
        $fields
    );
    return response('');
})->name('post');

但是,这会返回以下响应:

NULL
NULL
array(2) {
[0]=>
string(4) "John"
[1]=>
string(3) "Doe"
}

(表单填写的值是“firstname”=>“John”和“lastname”=>“Doe”)

是否可以使用相应的键(“名字”和“姓氏”)而不是数字键来检索此表单中的数组输入,还是我必须手动指定所有键?

【问题讨论】:

  • 尝试在刀片视图中添加 value="{{ $label }}"

标签: php laravel forms


【解决方案1】:

改变你访问输入的方式

$fields = $request->input("person");

你应该得到

array:2 [▼
  "firstname" => "John"
  "lastname" => "Doe"
]

使用该逻辑填充这些字段应该没有问题。如果您尝试在单个帖子中创建多个人,则需要在表单上使用额外的索引:

<form method="POST" action="">
  {{ csrf_field() }}
  @foreach(['firstname' => 'First Name', 'lastname' => 'Last Name'] as $key => $label)
  <label for="person[0][{{ $key }}]">{{ $label }}</label>
  <input name="person[0][{{ $key }}]" id="person[0][{{ $key }}]" type="text" />
  @endforeach
  <input type="submit" value="Send" />
</form>

在后端,循环访问:

for($request->input("person") AS $index => $fields){
  $person = new Person;
  $person->fill($fields);
}

// OR

$fields = $request->input("person.0");
$person = new Person;
$person->fill($fields);

在动态创建字段时,您需要一种方法来维护前端的索引,但这是一个不同的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2020-01-24
    相关资源
    最近更新 更多