사용자가 레이블과 값이있는 간단한 목록을 추가 할 수있는 기본 UI가 있습니다. 그 목록을 반복하여 "Detail"모델에 데이터를 저장하고 싶습니다.Laravel 5의 입력 배열을 반복합니다.
다음 코드가 있습니다.
컨트롤러 :
$details = $request->input('detail_label');
foreach($details as $key => $value)
{
if(!empty($request->input('detail_value.'.$key))) {
// if the detail has an existing ID
if($request->input('detail_id.'.$key)) {
$detail = Detail::find($request->input('detail_id.'.$key));
} else {
$detail = new Detail;
}
$detail->type = $request->input('detail_type.'.$key);
$detail->label = $request->input('detail_label.'.$key);
$detail->value = $request->input('detail_value.'.$key);
if($request->input('detail_privacy.'.$key) == 1) {
$detail->privacy = 1;
} else {
$detail->privacy = 0;
}
$user->details()->save($detail);
}
}
보기 : 나는 detail_privacy 필드를 제외하고 계획했던대로 내 코드의 모든 측면 작동
@foreach($user->details as $detail)
<div class="detail">
<input type="hidden" name="detail_id[]" value="{{ $detail->id }}">
<label>Type
<select name="detail_type[]">
<option @if($detail->type == '1')selected @endif value="1">Phone</option>
<option @if($detail->type == '2')selected @endif value="2">Phone (mobile)</option>
<option @if($detail->type == '3')selected @endif value="3">URL</option>
<option @if($detail->type == '4')selected @endif value="4">Email</option>
</select>
</label>
<label>Label
<input type="text" name="detail_label[]" value="{{ $detail->label }}">
</label>
<label>Value
<input type="text" name="detail_value[]" value="{{ $detail->value }}">
</label>
<label>Private?
<input type="checkbox" name="detail_privacy[]" @if($detail->privacy == true) checked @endif value="1">
</label>
<label>Delete?
<input type="checkbox" name="detail_delete[]" value="{{ $detail->id }}">
</label>
</div><!--/detail -->
@endforeach
. 부울 프라이버시 속성을 설정하고 설정을 해제하지만 원하는 $ 키에 아무런주의를 기울이지 않습니다. 그것은 항상 루프의 순서에 따라 설정합니다. 개인 정보를 하나만 설정하면 가장 먼저 표시됩니다. 내가 두 개를 설정하면 (둘 중 어느 것이 든), 그것은 첫 번째와 두 번째가 될 것입니다.
내 논리에는 분명히 잘못된 것이 있지만 무엇을 말할 수 없습니다.
도움이 될 것입니다. 감사!
왜 필드에 대한 모든 이름을 배열로 사용 했습니까? – iLLin
@iLLin -이 상황에서 내 대안은 무엇입니까? –
이 질문에 왜 투표가 내려 졌습니까? –