简体   繁体   English

在 null 上调用成员 function save():更新中的问题

[英]Call to a member function save() on null: PROBLEM IN UPDATING

I cannot update my record using foreach我无法使用 foreach 更新我的记录

ScoreController.php ScoreController.php

public function updateScore(Request $request, $id)
{
     foreach ($request->score as $key => $id) {

        $scores =  Score::find($request->score[$key]); 
        $scores->save();
        }
    //dd($request->all());
    return redirect('/tabulation')->with('status', 'Score added!');
}

Blade

@foreach ($scores as $score)
<label for="{{$score->id}}" value="{{$score->id}}"></label>
<input type="text" name="score[]" value="{{$score->score}}"/>
@endforeach

First of all, <label> elements do not have a value attribute:首先, <label>元素没有value属性:

<label for="{{ $score->id }}" value="{{ $score->id }}"></label>

That value="{{ $score->id }}" does nothing, and isn't sent to the server.value="{{ $score->id }}"什么都不做,也不会发送到服务器。 If you want to send the score's ID to the server, pass that in your input:如果您想将分数的 ID 发送到服务器,请将其传递到您的输入中:

@foreach($scores AS $score)
<input type="text" name="scores[{{ $score->id }}]" value="{{ $score->score }}"/>
@endforeach

Next, in your controller, access your variables correctly:接下来,在您的 controller 中,正确访问您的变量:

foreach($request->input("scores") AS $id => $scoreValue){
  $score = Score::find($id);
  $score->score = $scoreValue;
  $score->save();
}

The reason you're getting Call to a member function save() on null is that you're trying to find a Score that has an id of whatever $score->score contains.您在 null 上收到Call to a member function save() on null是您试图找到一个 ID 为$score->score Score的任何分数的分数。 You're not passing or referencing the id correctly.您没有正确传递或引用id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM