Laravel and Images validation - laravel

I have a little question about Laravel ...
I have a big form with which it is possible to send images.
I did a "PageStoreRequest" with my validation rules and everything works fine.
Depending on the length of the form, I would like that if an image is not valid, it is simply "deleted" (or "ignored") from the form and that the rest of the form is treated correctly ... So that the rest of the images are not to be sent again ...
I wonder if there is a method that would check a single field?
(like my Image Field)
And if it is not valid, delete it?
(knowing that the other fields must also pass to the Validator)
Thanks for your ideas :)

You can validate image field.
$request->validate([
'image' => 'mimes:jpeg,jpg,png'
]);
And then field is validated;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
// Make something
}

Related

Best strategy to avoid Ajax roundtrips when updating databases in Laravel

Let's say I have a table with data in the rows coming from a database. On each row of this table there are helper buttons. These buttons perform instant operations on the database, such as setting a status code (for example sold, blocked, in progress), changing an invoice date for the row (for example from 18/11/2022 to null) and so on..
What I would like is that when a user clicks on one of these buttons, an ajax function will performs a request to the related controller that will show a modal box asking for confirmation (not a JS alert but HTML code that comes from a blade component).
So, giving a basic example in the case of the change of status code for the row, what I would do is first set up a route of this type:
Route::post('/status', [TableController::class, 'status']);
after that i will build my controller(using the related model Table) in a way that if the action value coming from the ajax request is confirm(the one coming from the confirmation modal), I will continue with the data update, if instead the action is something different such as status(the one coming from the helper button), then I will bring up my confirmation modal
class TableController extends Controller {
// Change status
public function status(Request $request){
if( $request['action'] == 'confirm' ) {
// Update DB
Table::where('id', $request->id)->update(['status' => 822]);
} else {
$id = $request->id;
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />',
[
"title" => "Vuoi bloccare le seguenti disponibilità? ".$id ?,
"action" => "status",
"id" => $id
]);
}
}
If you notice the return of component part here
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />'
I'm passing to the component the id of the row, and the action to perform, those datas will be usefull for the next ajax request coming from the confirmation modal, that will update the row in the database. But basically what is happening here?
Send data from frontend to the controller(id of the row, status action, status code).
Send back the same data from the backend to modal component to fill the ajax confirmation request.
Resend back to the server the same data to catch the confirm statement and update the database.
This kind of approach always worked for me, but when things becomes complex(let's say that I have different kind of helpers like I said before, in example remove a date, change the owner, set some flags etc) this will become a mess, because I have everytime to send back the same data that I just received.
So my question:
Is there a way to avoid this thing to sending back and forward those datas? like something in the middle that stores what am I doing in the current session and can inform the modal box without this round trip? Also i am really thinking that my approach is completely wrong and out of mind, so i have to see things from a different point of view? This is because I am self-taught so I certainly have some gaps that I would like to fill.

laravel image validation sometimes works

I have a simple validation rule, to just require a photo being uploaded
yet, some images go through no problem, and some of them tell me, 'image required'.
Am I missing something in my code? what would let some get through and some not?
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
rules = array('image' => 'required',);

Symfony2, dynamically refresh form choices

I am creating a simple Blog system with symfony2. Each blog Post is bound to a certain amount of Tags.
Tags can be selected with checkboxes when creating a new blog post. Now I want to be able to dynamically add new tag-checkboxes to the form.
The AJAX part is done and working, I can add new tag names to the Tag entity and append the new checkboxes to the form.
The problem is when I submit the form, symfony2 doesn't recognize the new added tags because they don't belong to the Tag entity yet (at the time the form was generated).
For example: after submitting the form, I dump:
$tags = $form->get('tags')->getData();
The controller ignores the tags that were added through ajax.
I know it has to be solved with events somehow, I already read this documentation: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html but can't figure out how to implement it for this specific case.
Here is my form builder for "PostType":
$builder
->add('title')
->add('content', 'textarea')
->add('tags', 'entity', array(
'class' => 'Bundle:Tag',
'property' => 'name',
'multiple' => true,
'expanded' => true,
))
->add('save', 'submit')
;
You can try to use this: Form Collection
Make sure you persist the newly added Tags before submit the form, and the checkboxes has the right names and values.
Names should be like "post[tags][]" and values should be the database ids of the Tag entities.

How to Repopulate a form field without setting rule as required in Codeigniter?

When I try to populate a form field which is not required in form validation doesn't repopulate. Let's say I have a field but I don't want it to be required but I want it to be repopulated. How can I do it ? I think this is a bug for codeigniter.
This piece of code solved my problem. But I have to use helpers for that. At least I have a solution.
function value_field($field, $default='') {
return (isset($_POST[$field])) ? $_POST[$field] : $default;
}
You have to set a validation rule on a field in order for it to repopulate on an invalid submission. Luckily, you can pass regular PHP functions, not just validation rules, to the set_rules() method so you could just set trim or something rather than required.
$this->form_validation->set_rules('your_field', 'Your Label', 'trim');
That will repopulate the field and not make it a required field.
Using the form helper's set_value() works even for non-required fields, I'm not sure where your problem lies...
echo form_input(array('name' => 'username', 'value' => set_value('username'));

CodeIgniter Form Validation with existing $_POST data

I have a form that I need to validate but I can't figure out how to code the controller so that it works correctly the first time the page is displayed. Here is my code (simplified):
function index()
$data['somedata'] = $this->input->post('somedata');
$this->form_validation->set_rules('event', 'Event', 'trim|required|alpha_numeric');
... more set_rules ...
if($this->form_validation->run() == FALSE)
{
// Hasn't been run or there are validation errors
$this->load->view('eventview', $data);
}
else
{
// Process the event
}
}
The problem is that form_validation->run() is never FALSE because the $_POST array contains data from a previous form that is used by this second form. At the very beginning of the form_validation->run() function is the following code:
// Do we even have any data to process? Mm?
if (count($_POST) == 0)
{
return FALSE;
}
Since $_POST data exists the count is always greater than zero which results in the validation to be processed on initial page load.
Any suggestions as to how I might work around this?
I would suggest that you save the data from your first form in sessions, then make a redirect to your second form instead of going directly to the next one, with your post data.
This would also be more flexible if you need to reuse any of the submitted data.
In the first form set a hidden input
<input type="hidden" name="form1" value="form1" />
Then in your controller check if the field is set, if so store the current post array, and then unset it.
if(isset($_POST['form1'])){
$old_post = $_POST;
unset($_POST);
}
as I assume you are accessing the $_POST array in your view, instead pass `$old_post` through and use that,
e.g. (isset($old_post) ? $old_post['field_name'] : set_value('field_name))
Good luck.

Resources