Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Andi1982's avatar

Add Validation error to validator and make it fail

I have an image upload and want to check if it is an image and also if the user already has max 4 allowed images reached.

But the validator never fails ( $validator->fails() ), if just my own added error is there. How can I make the validation to failed?

        $validator = \Validator::make($request->all(), [
            'img' => 'required|image|mimes:jpg,jpeg,png'
        ]);

        $countMedia = Media::where('bet_id', $bet->id)
            ->where('type', 'bet_image')
            ->count();


        if ($countMedia >= 4) {
            $validator->getMessageBag()->add('img', __('Max 4 images allowed!'));
        }

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()]);
        }
0 likes
4 replies
Nakov's avatar

You can do this:

// add this import
use Illuminate\Validation\ValidationException;

if ($countMedia >= 4) {
	throw ValidationException::withMessages(['img' => __('Max 4 images allowed!')]);
}
tykus's avatar

You can make a custom validation rule:

// App\Rules\ImageCount
public function __construct($Bet $bet)
{
	$this->bet = $bet;
}
public function passes($attribute, $value)
{
    return Media::where('bet_id', $this->bet->id)->where('type', 'bet_image')->count() <= 4;
}

public function message()
{
        return 'Max 4 images allowed!'
}
$validator = \Validator::make($request->all(), [
    'img' => ['required', 'image', 'mimes:jpg,jpeg,png', new ImageCount($bet)]
]);

Swaz's avatar

You can do additional validation like this with the after() method on the validator. I usually keep everything in a form request. Here's how that might look:

namespace App\Http\Requests;

use App\Models\Media;
use Illuminate\Foundation\Http\FormRequest;

class ImageRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

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

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->hasMaxImages()) {
                $validator->errors()->add('img', __('Max 4 images allowed!'));
            }
        });
    }

    private function hasMaxImages()
    {
        return Media::where('bet_id', $this->bet->id)
            ->where('type', 'bet_image')
            ->count() >= 4;
    }
}
1 like
Andi1982's avatar

Thanks, I did not know about the after() function. was reading, but did not understand at first. Thanks a lot for this hint!

Please or to participate in this conversation.