2017-08-30 20 views
0

我有這樣的問題:for循環,通過輸入的檢索和價值

當我通過50輸入的for循環,我只填充到第一輸入請求/後返回null。但是當我填寫最後一個輸入時,它會返回值。

控制器代碼

public function store(Request $request) 
{ 
    $data = $request->get('type'); 

    $country = Country::create([ 
      'user_id' => '1', 
      'country' => $data['name'] 
    ]); 
} 

這是形式

<div class="container"> 
    <form action="/form" method="post"> 
     {{csrf_field()}} 
     @for($x = 0; $x++ < 50;) 
      <input type="text" name="type[name]"> 
     @endfor 

     <button type="submit">Submit</button> 
    </form> 
</div> 
+3

您需要數組輸入,爲此''改變此'在你的控制器,你必須通過輸入數組,將到達插入您的模型 –

+0

嗯oke的工作,但我的情況是,我有2個輸入,類型[id]和類型[名稱]。我怎麼會在控制器中捕捉到? – frogeyedman

+0

所以你有50個輸入或兩個輸入? –

回答

0

好了,我結合從@ravinder和@u_mulder答案。這是爲我工作的解決方案。

形式:

<form action="/form" method="post"> 
{{csrf_field()}} 
@for($x = 0; $x++ < 50;) 
    <input type="text" name="type[{{$x}}][id]"> 
    <input type="text" name="type[{{$x}}][name]"> 
@endfor 
<button type="submit">Submit</button> 

控制器

public function store(Request $request) 
{ 

    foreach ($request->type as $value) { 
     if(!empty($value['id']) && !empty($value['name'])) { // if they are not empty proceed 
      $country = Country::create([ // Create a country 
       'user_id' => $value['id'], 
       'country' => $value['name'], 
      ]); 
     } 
    } 
} 

感謝您的幫助傢伙!

2

你輸入的名字是不正確的。如果你想有多個同名的輸入,你可以聲明它爲一個數組。

在HTML中替換

{{csrf_field()}} 
@for($x = 0; $x++ < 50;) 
    <input type="text" name="type[name]"> 
@endfor 

{{csrf_field()}} 
@for($x = 0; $x++ < 50;) 
    <input type="text" name="name[]"> 
    <input type="text" name="id[]"> // since you said you have two inputs 
@endfor 

在你的控制器

迴路輸入數組,並添加代碼,將其插入到數據庫中。

public function store(Request $request) 
{ 
    $names = $request->get('name'); // get posted name array 
    $ids = $request->get('id'); // get posted id array 
    if(!empty($id) && !empty($name)){ // validations 
     foreach($names as $key=>$value){ 
     // you can add more validations here 
     $country = Country::create([ 
      'user_id' => $ids[$key], 
      'country' => $value 
     ]); 
     } 
    } 
} 
2

很難理解什麼是你想實現但:

<form action="/form" method="post"> 
    {{csrf_field()}} 
    @for($x = 0; $x++ < 50;) 
     <input type="text" name="type[{{$x}}][id]"> 
     <input type="text" name="type[{{$x}}][name]"> 
    @endfor 

    <button type="submit">Submit</button> 
</form> 

這是你的表格。在name屬性中明確設置索引。在這種情況下,您$request->type看起來像:

array(
    0 => array(id => value0, name => value0) 
    1 => array(id => value1, name => value1) 
    // more items 
) 

在控制器,你可以迭代它:

foreach ($request->type as $value) { 
    $country = Country::create([ 
     // don't know where you should put id, but 
     'id_key' => $value['id'], 
     'country' => $value['name'], 
    ]); 
} 
+0

是的,這項工作的好方案!現在我必須找出當$值爲空時要做什麼。 – frogeyedman

+0

如果名稱或ID爲空,請檢查'空'並且不要插入。 –