Laravel存储for-each循环中的值并将其作为数组传递

时间:2018-06-27 03:33:47

标签: php laravel

我的创建视图[Subject_id,Lead_id]中有两个for-each循环,我想使用数组方法将for-each值存储到数据库中,但是任何人都可以修改我的代码或为我指出正确的方法。

控制器:

public function store(Request $request)
{
    //
    $input = $request->all();
    $items = array(['Subject_id','Lead_id']);
    foreach($input as $inputs) {
        $items[] = $inputs;
    }
    $scores = new Score();
    $scores->Subject_id=$items['Subject_id'];
    $scores->Lead_id=$items['Lead_id'];
    $scores->save();
    dd($request->all());
    return redirect()->route('scores.create')->with('notif', 'Success.');
}

这是消息: enter image description here

创建视图

@foreach ($leads as $lead)
    <tr>
        <td>{{ $lead->student_name }}</td>
        <td><input type="checkbox" class="checkbox" name="Lead_id[]"  value="{{ $lead->id }}"></td>
    </tr>
@endforeach
@foreach($subjects as $subject)
 <label >
    <input type="checkbox" name="Subject_id[]" value="{{ $subject->id }}">
    {{ $subject->subject_name }}
 </label>
 @endforeach

DD结果:enter image description here

3 个答案:

答案 0 :(得分:1)

在控制器中尝试此代码

configurations.all {
    resolutionStrategy.dependencySubstitution {
        substitute module('org.apache.commons:commons-io:1.3.2') with module('commons-io:commons-io:1.3.2')
    }
}

答案 1 :(得分:0)

更新您的刀片服务器

    @foreach ($leads as $lead)
    {{ $lead->student_name }}
        @foreach($subjects as $subject)
          <input type="checkbox" name="Subject_id[$lead->id][]" value="{{ $subject->id }}">
          {{ $subject->subject_name }}
        @endforeach
   @endforeach

这是您的控制器

   public function store(Request $request)
    {
        //
    $subjects = $request->get('Subject_id');

       foreach($subjects as $key=>$oneLeadOptions) {

           foreach($oneLeadOptions as $option){
                  $scores = new Score();
                  $scores->Subject_id  = $option;
                  $scores->Lead_id = $key;
                  $scores->save();

           }
       }
    //To to other redirects logic here
    }

尝试

答案 2 :(得分:0)

每次都以一种无效的方式在foreach循环中创建模型的实例。您可以这样做

   foreach($input as $inputs) {
     $dataArray[] = [
    'Subject_id' => $inputs['Subject_id'],
    'Lead_id' => $inputs['Lead_id'],
    ];    
    }
DB::table('Score')->insert($dataArray);

您可以根据需要操纵数据。

使用此代码,我有这个enter image description here