I have problem when validating inputs. All input fields pass the validation process except image fields.
This is my file upload code in html:
<div class="control-group">
<label class="control-label" for="fileInput"> Cover picture: </label>
<div class="controls">
{!! Form::file('cover') !!}
</div>
</div>
And how I get data from view in controller:
$datas = array(
'name' => Input::get('name'),
'color' => Input::get('color'),
'size' => Input::get('size'),
'cover' => array('cover' => Input::file('cover'))
);
And this is rules:
$rules = array(
'name' => 'required',
'color' => 'required',
'size' => 'required',
'cover' => 'required|mimes:jpeg,jpg,png|max:10000'
);
And Validation facades`s make method:
$validator = Validator::make($datas, $rules);
As I mentioned earlier, all validation rules passed for input, but for image it gives me an error:
The cover must be a file of type: jpeg, jpg, png.
Now, how can I fix it?
I think you should approach this a little differently...
If you instead just create your function like so..
// The Illumniate/Http/Request version of Request in laravel
public function yourFunction(Request $request){
....
$rules = ...;
$validator = Validator::make($request->all(), $rules);
}
The expected format of the Validator is handled automatically because it returns it. And when it runs through you can handle everything the same you already have.
Since this is accepted. The way to actually fix it with the code above is to just remove the multi-dimensional array and just use Input::file('cover') as it returns an array on its own.
Related
This is most likely a duplicate question but I have been looking for solutions and can't seem to find one that fixes the issue I have. I have created a function called validateRequest which validates all the fields. This function is then called in store function $post = Post::create($this->validateRequest()); I have made sure in the HTML form enctype="multipart/form-data" has been included, but every time a submit a new entry that errors appear. Not sure if I am using the return tap method correctly or something else, really appreciate some help thanks.
public function validateRequest()
{
return tap(
$validated = request()->validate([
'title' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
'content' => 'required|string',
'active' => 'integer'
]), function () {
if (request()->hasFile('image')){
request()->validate([
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
]);
}
// Check if active is ticked
$validated['active'] = isset(request()->active[0]) ? 1 : 0;
// Create slug from title
$validated['slug'] = Str::slug(request()['title'], '-');
});
}
"files" is not a valid validator, use file without "s"
'image' => 'sometimes|files|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
Hope this helps
I am working on a Laravel 5.5 project which is giving me some issues... One of them is that when I upload some image it returns me an error: "The file must be an image" with the following code in the controller.`
public function update(\App\Property $property, Request $request)
{
$rules = [
'images.*' => 'mimes:image|max:2048',
'zone' => 'required'
];
$messages = [
'images.mimes' => 'The file must be an image', // in my file that is a translated of the original message
'images.max' => 'The images sizes must be under 2MB',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()) {
parent::message(
$validator->errors(),
'¡Error!',
'error'
);
return back()->withInput();
}
Just in case:
I was reading some people who had the same issue but in my case I have the usual <form method="POST action="..." enctype="multipart/form-data">
I made a dd($request->files) on the request but the all the images I upload seems to be images.
Also I've tried to use the iteration method as following:
if($request->hasFile('images')) {
foreach ($images as $image)
{
$validator = Validator::make(
[ 'image' => $image ],
[ 'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048' ],
[
'image.mimes' => 'Images must have format (JPEG, PNG, JPG, GIF or SVG)',
'image.max' => 'Each image must be under 2MB'
]);
if($validator->fails()) {
parent::message(
$validator->errors(),
'¡Error!',
'error'
);
return back()->withInput();
}
}
}
But when the images are too bigger than 2MB the request is not even passing through if($request->hasFile() function.
And I want a generic error for all the images and not validate every image, is that possible? By the way in the Laravel Documentation it hasn't the previous iterating method.
I was trying to figure this out as well and it seems symfony has been updated since Laravel 5.5. On Laravel 8 I can tell you that the following combination of settings fixed the error I had yielding the same error type you had:
In your form:
make sure your form has
<form method="POST action="..." enctype="multipart/form-data">
In your validator:
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
In the event that you are using Laravel Collectives for your form, then you can implement the enctype as show below :
{!! Form::open([‘action’ =>’ProfilesController#update’,
‘method’ => ‘POST’, ‘enctype’ => ‘multipart/form-data’]) !!}
I have a form with an input which allows to upload PDFs.
Here is the method that validates my input :
protected function validator(array $data)
{
return Validator::make($data, [
'title' => 'required|max:255|string',
'artist' => 'required',
'notes' => 'nullable|string',
'file' => 'required|mimes:pdf|max:500',
'g-recaptcha-response' => 'required|captcha',
]);
}
The rules are working for all the other fields, but it does not work for the file input. Whatever I upload, PDF or not, I have the following error :
The file must be a file of type: pdf.
I just solved my issue.
In case someone has the same problem, you need to set the enctype attribute of your form to multipart/form-data.
In short, something like this :
<form action="#" enctype="multipart/form-data">
...
</form>
The error is not very clear, so I hope this helps.
How can I perform validation on custom array in Lumen framework. e.g:
Example array:
$params = array('name' => 'john', 'gender' => 'male');
I have tried something like this but didn;t work:
$validator = Validator::make($params, [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
echo $message;
exit;
}
The validation is passing because the fields are in fact present. Use something like min or maxor size to validate the length of a string.
http://lumen.laravel.com/docs/validation#rule-required
Edit
I stand corrected. The required does actually seem to validate if it contains anything.
Update
To clarify; the code that is supposed to run if $validator->fails() doesn't ever run if the validation passes.
I'm using this datamapper http://datamapper.wanwizard.eu
problem is datamapper have validation methods similar with codeigniter form validation.but not as same.
An example, a model admins model validation array:
public $validation = array(
'username' => array(
'rules' => array('unique', 'required', 'trim', 'max_length' => 60, 'min_length' => 3),
'label' => 'User'
),
'password' => array(
'rules' => array('required', 'trim', 'encrypt', 'min_length' => 6),
'label' => 'Password'
)
);
but form validation array must be like that:
public $form_validation = array(
array(
'field' => 'username',
'label' => 'User',
'rules' => 'unique|required|trim|max_length[60]|min_length[3]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|encrypt|min_length[6]'
)
);
I don't want to make two manual validation for new admin adding (first form validation, after datamapper validation). I think there is a way to make this with just one manual validation.
sorry my bad English, I hope you understand. Thanks in advance.
Using the Datamapper's validation alone should be enough, without the CI's form library.
When you try to save the model, the save() method will return a true or false depending on if the save was successful. If it isn't the model's error property should be filled with the error messages generated for the validation that failed. The messages can be loaded from language files with keys named appropriately, also the codeigniter's form validation library's form_validaton_lang.php is loaded too.
In your controller you could make use of them like this:
Class TheController extends CI_Controller {
function save() {
// get the model object somehow
// ...
// update attributes
$model->prop0 = $this->input->post('prop0');
$model->prop1 = $this->input->post('prop1');
// try to save it
if ($model->save()) {
// save successful
redirect(...);
} else {
// save failed load form again, with the model
$this->load->view('path/to/the/form', array('model' => $model));
}
}
}
The view could work like this:
<form method="post" action="...">
<label>prop0</label>
<input type="text" name="prop0" value="<?php print $model->prop0?> ">
<?php if (!empty($model->error->prop0)):?>
<div class="error"><?php print $model->error->prop1; ?></div>
<?php endif; ?>
<label>prop1</label>
<input type="text" name="prop1" value="<?php print $model->prop1?> ">
<?php if (!empty($model->error->prop0)):?>
<div class="error"><?php print $model->error->prop1; ?></div>
<?php endif; ?>
<buton type="submit">go</button>
</form>
The same form can be used when no previous model exists in the database, just create an empty instance of the model you need, and pass it to the form.