dannyhma's avatar

Updating the image is not working.

Hello everyone, I’d like to ask for some help. I’m trying to update an image in Laravel + Inertia. However, I’m encountering an issue where updating the image doesn’t work. When I upload an image, an error message appears saying title.required and description.required. On the other hand, if I don’t upload an image, I get an error message for image_file.mimes. When I remove the mimes rule, I can successfully update the Title and Description only. What should I do to fix my code? Thank you.

My Controller:

public function update(UpdateArticleRequest $request, $id)
{
    $articles = Article::findOrFail($id);

    $articles->title = $request->title;
    $articles->description = $request->description;
    if ($request->hasFile('image_file')) {
        $file = $request->file('image_file');
        $name = $file->hashName();

        Storage::putFileAs('images', $file, $name);
        if ($articles->image) {
            Storage::delete('images/' . $articles->image);
        }

        $articles->image = $name;
    }

    $articles->update();

    return redirect()->route('articles.index')->with('success', 'Article updated successfully.');
}

My Request:

public function rules(): array
{
    return [
        'title' => [
            'required',
            'min:5'
        ],
        'description' => [
            'required',
        ],
        'image_file' => [
            'nullable',
            'mimes:jpg,jpeg,png'
        ]
    ];
}								
						
public function messages()
{
    return [
        'title.required' => 'The title field cannot be empty.',
        'title.min' => 'The name must be at least 5 characters long.',
        'description.required' => 'The description field cannot be empty.',
        'image_file.mimes' => 'The image must be in jpg, jpeg, or png format.',
    ];
}

My Vue:

								<input
									class="block w-full cursor-pointer rounded-lg border border-gray-300 bg-gray-50 text-sm text-gray-900 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:placeholder-gray-400"
									@change="form.image_file = $event.target.files[0]"
									multiple
									type="file"
									id="image_file"
									name="image_file"
								/>
0 likes
2 replies
Tray2's avatar

It basically means that you need to pass all the values from the form into you you controller.

If you don't want to do that, you need to create a new controller just for updating the image.

Please or to participate in this conversation.