0
votes

I want to update some data from the DB, so I added this Controller method:

public function updateAnswer(Answer $anss)
    {
        $validate_data = Validator::make(request()->all(),[
           'answer' => 'required'
        ])->validated();

        $answer = Answer::findOrFail($anss);
        $answer->update($validate_data);
        return back();
    }

Now the problem is I get this error:

Method Illuminate\Database\Eloquent\Collection::update does not exist.

So how to solve this issue?

2
$answer()->update($validate_data) here $answer is collection so make it DB instance like $answer() - Kamlesh Paul
Look into it i think this is helpful stackoverflow.com/questions/46115064/… - Irshad Khan

2 Answers

2
votes

You are already resolving $anss using route-model binding.

public function updateAnswer(Answer $anss)

You are trying to call findOrFail with a model as an argument, which since Model implements Arrayable will return a Collection, thus breaking the update call.

See Illuminate\Database\Eloquent\Builder findOrFail -> find -> findMany -> return $this->whereKey($ids)->get($columns);.

Try:

    public function updateAnswer(Answer $anss)
    {
        $validate_data = Validator::make(request()->all(),[
           'answer' => 'required'
        ])->validated();

        $anss->update($validate_data);

        return back();
    }

0
votes

$anss is already an Answer object so you do not need to query it from the database.

$anss->answer = $validate_data['answer'];
$anss->save();

or

Answer::where('id', $anss->id)
    ->update($validate_data);