0
votes

I have a Laravel program that saves form data and uploads a few pictures. In the validation, there are two rules. The image is required and it has to be of image type (jpg, jpeg, png). However, the validation only checks for the filetype and does not check for 'required'. Even if there is no image, it allows the user to submit. Why?

public function updateImages(Request $request, $id)
{
    $validatedData = $request->validate([
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg|max:2048',
    ],
        [
            'image.*.image' => 'Format Error: Please uplaod image in a png or jpg format',
        ]);
    $item = Post::find($id);
    $existing_count = Photo::where('post', $item->id)->count();
    $countrequest = sizeof($request->file('image'));
    $count = $existing_count + $countrequest;
    if ($count >= 6) {
        return back()
            ->withInput()
            ->withErrors(['Only 5 images can be uploaded!']);
    }
    $upload = $this->imageUpload($item, $request);

    return redirect()->back()->with('message', 'Image Updated');
}
2
Why are you doing image.*? Why not put all the validation under image ? - Kyle Wardle

2 Answers

0
votes

Apply require with image.*. Eg.-

image.*' => 'require|image|mimes:jpeg,png,jpg|max:2048', 

Try this solution. It will work.

0
votes

You can use Laravel Request Validation

To create a form request class

php artisan make:request ImageUpdateRequest

Go to app/Http/Requests add the rules

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
    ];
}

On your controller

use App\Http\Request\ImageUpdateRequest;

public function updateImages(ImageUpdateRequest $request, $id)
{
    $item = Post::find($id);
    $existing_count = Photo::where('post',$item->id)->count();
    $countrequest = sizeof($request->file('image'));
    $count= $existing_count+$countrequest;
    if ($count >= 6 ){
        return back()
        ->withInput()
        ->withErrors(['Only 5 images can be uploaded!']);
    }
    $upload = $this->imageUpload($item, $request);
    return redirect()->back()->with('message', 'Image Updated');
}