Not sure, but shouldn't it work if you add sometimes to your state.product_image validation rule? https://laravel.com/docs/10.x/validation#validating-when-present
Jun 28, 2023
6
Level 2
Update product problem laravel / livewire
Hi Folks, I'm trying to update a product without the need to redo the uploads again, of course if necessary be able to upload a new image, but for some reason I'm getting The state.product image field must be an image. The state.product image field must be a file of type: jpg, png., even though the field is set to null at creation, even without an image it works fine, but in the update I am facing this problem. Can anybody help me? Thank you in advance for all help welcome.
Follow the code.
class EditProduct extends Component { use WithFileUploads;
public Product $product;
public $uploads = [];
public $files = [];
public $existingFiles = [];
public $removedFiles = [];
public $state = [
'title' => null,
'slug' => null,
'description' => null,
'price' => '0.00',
'live' => false,
'product_image' => null,
'files.*' => null,
];
public function rules()
{
return [
'state.title' => 'required|max:255',
'state.slug' => 'required|max:255|unique:products,slug,' . $this->product->id,
'state.description' => 'required',
'state.price' => 'required|decimal:0,2|min:1',
'state.live' => 'boolean',
'state.product_image' => 'nullable|image|mimes:jpg,png|max:2048',
'files.*' => 'required|mimes:zip|max:98048',
];
}
public function mount()
{
$this->state = $this->product->withoutRelations()->toArray();
$this->state['price'] = money($this->state['price']['amount'])->formatByDecimal();
$this->existingFiles = $this->product->files;
}
public function submit()
{
$this->validate();
if ($this->state['product_image']) {
$imagePath = $this->state['product_image']->store('public/product_image');
$this->state['product_image'] = Storage::url($imagePath);
} else {
unset($this->state['product_image']);
}
$this->product->update($this->state);
$files = collect($this->files)->map(function ($file) {
return File::make([
'filename' => $file->getClientOriginalName(),
'path' => $file->store('files')
]);
});
$this->product->files()->saveMany($files);
$this->product->files()->whereIn('id', $this->removedFiles)->delete();
$this->dispatchBrowserEvent('alert', 'Product updated!');
}
Please or to participate in this conversation.