How can I limit the number of files that can be uploaded?
The max
validation seems to apply to the size of the image (in kilobytes). How can I make a va
In laravel, there is no built-in validation rule for that. But you can create custom-validation rule to handle this.
Here is a simple custom-validation rule for it.
Create customValidator.php
in app/
directory.
Validator::extend('upload_count', function($attribute, $value, $parameters)
{
$files = Input::file($parameters[0]);
return (count($files) <= $parameters[1]) ? true : false;
});
Don't forget to add it to app/start/global.php
require app_path().'/customValidator.php';
In your validation setting,
$messages = array(
'upload_count' => 'The :attribute field cannot be more than 3.',
);
$validator = Validator::make(
Input::all(),
array('file' => array('upload_count:file,3')), // first param is field name and second is max count
$messages
);
if ($validator->fails()) {
// show validation error
}
Hope it will be useful for you.
How I did in laravel 7.x
Create a new form request class with the following command
php artisan make:request UploadImageRequest
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Requests\BaseFormRequest;
class UploadImageRequest extends BaseFormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'coverImage.*' => 'image|mimes:png,jpg,jpeg,gif,svg|max:2048',
'coverImage' => 'max:5',
];
}
public function messages() {
return [
'coverImage.*.max' => 'Image size should be less than 2mb',
'coverImage.*.mimes' => 'Only jpeg, png, bmp,tiff files are allowed.',
'coverImage.max' => 'Only 5 images are allowed'
];
}
in View.blade.php
<input type="file" id="coverImage" name="coverImage[]"
class="form-control-file @error('coverImage') is-invalid @enderror" multiple>
@error('coverImage')
<span class="text-danger">{{ $message }}</span>
@enderror
in controller
public function store(UploadImageRequest $request)
{
//code
}