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;
}
}