Reputation: 1051
I'm trying to update an item that could have an image or change the one that is already there, when I only change the image or add one it doesn't update, but if I change or add an image along with something else like the name or description then it does update both things. I'm not sure why this is happening.
I'm sending it to the controller like this
submit(item) {
let data = new FormData();
data.append('file', this.imagen);
data.append('name', this.ruleForm.name);
data.append('summary', this.ruleForm.summary);
data.append('description', this.ruleForm.description);
data.append('price', this.ruleForm.price);
data.append('hours', this.ruleForm.hours);
data.append('min_grade', this.ruleForm.min_grade);
data.append('matery', this.matery);
data.append('remover', this.remover);
data.append('strict', this.strict);
this.$refs.ruleForm.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/courses/' + item.id, data)
.then(
() => {
this.$message({
type: 'success',
message: 'Guardado correctamente.'
});
this.loading = false
},
(res) => {
this.$message.error(parseError(res)[0]);
this.loading = false;
})
} else {
return false;
}
});
},
This is the full update function in the controller
public function update(CourseSaveRequest $request, $id)
{
Log::info($request);
$editCourse = Course::find($id);
$editCourse->name = $request->name;
$editCourse->summary = $request->summary;
$editCourse->description = $request->description;
$editCourse->price = $request->price;
$editCourse->hours = $request->hours;
$editCourse->min_grade = $request->min_grade;
if ($request->hasFile('file')) {
$this->removeImage($editCourse);
$image = $request->file('file');
$imageName = Uuid::generate(4)->string . '.' . $image->getClientOriginalExtension();
$editCourse->image = '/' . 'img/courses' . '/' . $imageName;
$request->file('file')->move('img/courses', $imageName);
}
$editCourse->save();
return back();
}
private function removeImage(Course $course){
if (!empty($course->image) && file_exists(public_path($course->image))) {
unlink(public_path($course->image));
}
}
Not sure if this is relevant but this is the CourseSaveRequest
public function rules()
{
$rules = [
'name' => 'required|unique:courses',
'summary' => 'required',
'price' => 'required|numeric|min:0',
'hours' => 'required|numeric|min:0',
'min_grade' => 'required|numeric|min:0'
];
if ($this->has('id')) {
$rules['name'] .= ',id,'.$this->get('id');
}
return $rules;
}
Upvotes: 0
Views: 46
Reputation: 1979
I suspect it's the unique rule on the name, you can ignore the current model instance on unique with the following
use Illuminate\Validation\Rule;
...
public function rules()
{
$rules = [
'name' => [
'required',
Rule::unique('courses')->ignore($this->id)
],
'summary' => 'required',
'price' => 'required|numeric|min:0',
'hours' => 'required|numeric|min:0',
'min_grade' => 'required|numeric|min:0'
];
return $rules;
}
Upvotes: 1