laravel array validation only one required - laravel

Hello i have a form for image upload
<input type="file" name="ad_image[]">
i want only one image to be required and others to be optional.
This is my validation rule and is not working:
'ad_image.*' => 'required|min:1|mimes:png,gif,jpeg,jpg|max:300',
i have tryed this:
'ad_image' => 'required|array|min:1|mimes:png,gif,jpeg,jpg|max:300',
also not working, when i upload jpg file there is error "The ad image must be a file of type: png, gif, jpeg, jpg."
please help with this issue

You can try:
public function rules()
{
$rules = [
'ad_image0'=> 'image|required|mimes:png,gif,jpeg,jpg|max:300'
];
$nbr = count($this->input('ad_image')) - 1;
foreach(range(0, $nbr) as $index) {
$rules['ad_image.' . $index] ='image|mimes:png,gif,jpeg,jpg|max:300';
}
return $rules;
}

I have decided to make my own custom validation rule:
This code is in boot method of the AppServiceProvider
public function boot()
{
Validator::extend('require_one_of_array', function($attribute, $value, $parameters, $validator) {
if(!is_array($value)){
return false;
}
foreach ($value as $k => $v){
if(!empty($v)){
return true;
}
}
return false;
});
}
The validation message is manualy added as third parameter of the validator
$messages = [
'require_one_of_array' => 'You need to upload at least one pic.',
];
And this is how is used to make sure at lease one image is uploaded (this is in rules array):
'ad_image' => 'require_one_of_array',
'ad_image.*' => 'mimes:jpeg,bmp,png|max:300',

Related

Vue / Laravel: How to validate files uploaded from the frontend?

I have an image uploader on my Vue app that takes multiple files. I want to ensure they are images and of a certain size and if not, obviously don't upload the files and have the frontend display the error. Right now, the route it hits in the controller loos like this:
public function uploadAssets(UploadAssetsFormRequest $request)
{
if ($request->hasFile('file')) {
$files = $request->file('file');
$stack = [];
foreach ($files as $file) {
$fileName = Storage::put('/check/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
array_push($stack, $fileName);
}
return response()->json($stack);
}
}
My Form Request is below and has the validation but I don't know how to apply that in the controller.
UploadAssetsFormRequest
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class UploadAssetsFormRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'files.*' => 'required|image|max:1000',
];
}
public function messages()
{
return [
'files.*.max' => 'The image is too large',
'files.*.image' => 'Only image files are allowed.',
];
}
}
You need to check files extension :
$extension = $file->extension();
$allowed_file_types = ['jpg','png','gif'];
if (in_array($extension, $allowed_file_types)){
//do upload
}else{
Continue;
}
for file sizes check this thread
You can use laravel image validation
$this->validate ($input, [
'files.*.image' => 'image|max:200',
]):
Note: max(size) is in Kilobytes
You can also use dimension rule
$this->validate ($input, [
'files.*.image' => 'dimensions:min_width=100,min_height=200'
]):
Laravel Image Validation
Laravel Image Dimensions Validation
You can set the following rule in your validation -
'file' => 'required|max:100|mimes:jpg,png,bmp' // 100kb, mimes must have image extensions

Laravel - request validation

I extedned request class to create my own valdiation rules. In that class I added my custom validation function. In function I check if tags are pass regEx and I would like to filter tags to remove tags shorter then 2 characters.
And later keep in request only tags that passed validation.
public function createPost(PostRequest $request)
{
dd($request->all()); //In this place I would like to keep only tags passed through validation not all tags recived in request
}
Is it possibile to do it? How to set it in Request class?
'tags' => [
'nullable',
'string',
function ($attribute, $value, $fail){
$tagsArray = explode(',', $value);
if(count($tagsArray) > 5) {
$fail(__('place.tags_max_limit'));
}
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return $tagsFiltered;
}
],
EDIT:
I think we miss understanding. I would like to after validation have only tags that returned in variable $tagsFiltered; Not the same as recived in input.
You have to create this custom regex rule and use it into rules() function.
Like so:
public function rules()
{
return [
'tag' => 'regex:/[^]{2,}/'
];
}
public function createPost(PostRequest $request)
{
$request->validated();
}
And then just call it via validated() function wherever you want.
first define validation rule with this command:
php artisan make:rule TagsFilter
navigate to TagsFilter rule file and define your filter on passes method:
public function passes($attribute, $value)
{
$tagsArray = explode(',', $value);
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return count($tagsArray) > 5 && count($tagsFiltered) > 0;
}
then include your rule in your validation on controller:
$request->validate([
'tags' => ['required', new TagsFilter],
]);

Validation for form not checking partly

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');
}
Apply require with image.*. Eg.-
image.*' => 'require|image|mimes:jpeg,png,jpg|max:2048',
Try this solution. It will work.
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');
}

yii2 custom validation not working

I need to compare 2 attribute value in the model and only if first value is lower than second value form can validate.I try with below code but it not worked.
controller
public function actionOpanningBalance(){
$model = new Bill();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \Yii::$app->user->identity->id;
$model->save();
}else{
return $this->render('OpanningBalance', [
'model' => $model,
]);
}
}
Model
public function rules()
{
return [
[['outlet_id', 'sr_id', 'bill_number', 'bill_date', 'created_at', 'created_date','bill_amount','credit_amount'], 'required'],
[['outlet_id', 'sr_id', 'created_at', 'updated_at'], 'integer'],
[['bill_date', 'd_slip_date', 'cheque_date', 'created_date', 'updated_date','status'], 'safe'],
[['bill_amount', 'cash_amount', 'cheque_amount', 'credit_amount'], 'number'],
[['comment'], 'string'],
['credit_amount',function compareValue($attribute,$param){
if($this->$attribute > $this->bill_amount){
$this->addError($attribute, 'Credit amount should less than Bill amount');
}],
[['bill_number', 'd_slip_no', 'bank', 'branch'], 'string', 'max' => 225],
[['cheque_number'], 'string', 'max' => 100],
[['bill_number'], 'unique']
];
}
}
It's going in to the validator function but not add the error like i wanted
$this->addError($attribute, 'Credit amount should less than Bill amount');
anyone can help me with this?
If the validation is not adding any error, it's most likely being skipped. The issue is most likely becasue of default rules behaviour whereby it skips empty or already error given values as per here: https://www.yiiframework.com/doc/guide/2.0/en/input-validation#inline-validators
Specifically:
By default, inline validators will not be applied if their associated attributes receive empty inputs or if they have already failed some validation rules. If you want to make sure a rule is always applied, you may configure the skipOnEmpty and/or skipOnError properties to be false in the rule declarations.
So you would need to set up the skipOnEmpty or skipOnError values depending on what works for you:
[
['country', 'validateCountry', 'skipOnEmpty' => false, 'skipOnError' => false],
]
Try this:
public function actionOpanningBalance(){
$model = new Bill();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->created_at = \Yii::$app->user->identity->id;
$model->save();
}else{
return $this->render('OpanningBalance', [
'model' => $model,
]);
}
}
For Validation
You can use anonymous function :
['credit_amount',function ($attribute, $params) {
if ($this->$attribute > $this->bill_amount)) {
$this->addError($attribute, 'Credit amount should less than Bill amount.');
return false;
}
}],
you can use like this below answer is also write
public function rules(){
return [
['credit_amount','custom_function_validation', 'on' =>'scenario'];
}
public function custom_function_validation($attribute){
// add custom validation
if ($this->$attribute < $this->cash_amount)
$this->addError($attribute,'Credit amount should less than Bill amount.');
}
I've made custom_function_validation working using 3rd params like this:
public function is18yo($attribute, $params, $validator)
{
$dobDate = new DateTime($this->$attribute);
$now = new DateTime();
if ($now->diff($dobDate)->y < 18) {
$validator->addError($this, $attribute, 'At least 18 years old');
return false;
}
}
This is a back end validation and it will trigger on submit only. So you can try something like this inside your validation function.
if (!$this->hasErrors()) {
// Your validation code goes here.
}
If you check the basic Yii2 app generated you can see that example in file models/LoginForm.php, there is a function named validatePassword.
Validation will trigger only after submitting the form.

Limit number of files that can be uploaded

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 validation for the maximum number of files allowed to be uploaded (for example, only 10 files can be uploaded from a single input)?
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
}
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.

Resources