Laravel update/edit using foreach loop

妖精的绣舞 提交于 2021-02-08 10:01:48

问题


I was trying to update my table but I couldn't make it work.. I always end up with the error:

Invalid argument supplied for foreach()

Here is my Controller:

 public function show_score($id)
    {

        $scores = Score::with(['lead','subject'])->where(['subject_id'=>$id])->get();

        return view('markbook.show_score',compact('scores'));
    }

    public function update_score(Request $request)
    {
        $id = $request->input('id');

         $scores = Score::find($id);
         foreach ($scores as $datas) {
         $datas->jan_ap=$request->input('jan_ap');
         $datas->jan_hm=$request->input('jan_hm');
         $datas->save();  

        }


    }

route:
Route::get('markbook/scores/{id}', 'MarkbookController@show_score' );
Route::post('markbook/scores', 'MarkbookController@update_score'); 

Here is my table I'm trying to loop the updated score:


回答1:


From chat discussion what found is that you want to update multiple scores, which is listed in tr, td. You can change it like this

Change in view

@foreach($scores as $score) 
    <tr> 
        <td>{{$score->lead->student_name}} <input type="hidden" name="scores[{{$loop->index}}][id]" value="{{$score->id}}"></td> 
        <td><input type="text" name="scores[{{$loop->index}}][jan_ap]" value="{{$score->jan_ap}}"></td> 
        <td><input type="text" name="scores[{{$loop->index}}][jan_hm]" value="{{$score->jan_hm}}"></td> 
    </tr> 
@endforeach 

Controller update score

public function update_score(Request $request) 
{ 
    $scores = $request->input('scores');  //here scores is the input array param 

    foreach($scores as $row){
        $score = Score::find($row['id']); 
        $score->jan_ap = $row['jan_ap']; 
        $score->jan_hm = $row['jan_hm']; 
        $score->save(); 
    }
} 



回答2:


Using Score::find($id) you're only ever going to return 1 result so there won't be anything to foreach over.

If you just want to update a single row in the table you don't need to foreach it.

You can simply run

$score = Score::find($request->input($id));
$score->jan_ap = $request->input('jan_ap');
$score->jan_hm = $request->input('jan_hm');
$score->save();

if you want to return multiple rows you need to change your find to a get()

so $scores = Score::where('something', $request->input('something))->get();

If you want to update every row in the table with the same information you'd do a:

$scores = Score::all();

That would return every row in the table.



来源:https://stackoverflow.com/questions/51299643/laravel-update-edit-using-foreach-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!