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 IlluminateDatabaseEloquentCollection::update does not exist.
So how to solve this issue?
Advertisement
Answer
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 IlluminateDatabaseEloquentBuilder
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(); }