Laravel update/edit using foreach loop

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:

enter image description here

2 answers

  • answered 2018-07-12 07:34 WebDevB

    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.

  • answered 2018-07-12 09:01 rkj

    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(); 
        }
    }