How to Validate Multiple Image in Laravel

First of all, I will assume you to create a form with multiple image upload, and you will need to validate the images is required when the request is in your store method instead of update method.

Let's imagine that your form like this.

<form action="/your-action-to-store" method="post" enctype="multipart/form-data">
    <div class="mb-4">
        <input type="file" name="images[]" id="images" multiple>
            <div class="invalid-feedback">{{ $message }}</div>

Now, let's request your form request, I think it'll be nice if we can assume it your blog post. So you may name it PostRequest.

php artisan make:request PostRequest

And then, we will need to open that file inside app/Http/Requests/PostRequest.php

use Illuminate\Routing\Route;
use Illuminate\Validation\Rule;

class PostRequest extends FormRequest
    public function authorize()
        return true;

    public function rules(Route $route)
        return [
            'images' => Rule::requiredIf($route->getActionMethod() == "store"),
            'images.*' => ['image', 'mimes:jpeg,png,jpg,gif,svg,webp', 'max:2048'],
            'title' => ['required'],

And now, in your store method you can use the PostRequest and bind to your store method like this:

use App\Http\Requests\PostRequest;
class PostController
    public function store (PostRequest $request) 
        // do anything

And you're done. And now you understand to not duplicate your validation rule when you want to update the "post".

Irsyad A. Panjaitan

Irsyad A. Panjaitan

    Published 31 March
  • Fillin:
  • Laravel
Irsyad Notes Since 1987 ™