Inserting extra comma while multi upload how to avoid this - laravel-5

here what i need to do for avoiding extra comma separater while upload the images.it takes one more image while upload the file.i used comma separater for the concatination.
Controller
$filename_new_get = "";
$count = Input::get('count');
for($i = 0 ; $i < $count ; $i++)
{
$file_more = Input::file('file_more'.$i);
$file_more_name = $file_more->getClientOriginalName();
$move_more_img = explode('.',$file_more_name);
$filename_new = $move_more_img[0].str_random(8).".".$move_more_img[1];
$newdestinationPath = '../assets/categoryimage/';
$uploadSuccess_new =Input::file('file_more'.$i)->move($newdestinationPath,$filename_new);
$filename_new_get .= $filename_new.",";
}
$inputs = Input::all();
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$move_img = explode('.',$filename);
$filename = $move_img[0].str_random(8).".".$move_img[1];
$destinationPath = '../assets/categoryimage/';
$uploadSuccess = Input::file('file')->move($destinationPath,$filename);
$file_name_insert = $filename . ",".$filename_new_get;
$data=array(
'new_category_image'=> $file_name_insert,
);
Views
<div class="col-lg-8" id="img_upload">
<input type="file" id="file0" name="file" style="background:none;width:185px;border:none;">no files
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;color:#F60;width:84px;" id="add_img_btn" >Add</a></p>
<input type="hidden" id="aid" value="1">
<input type="text" id="count" name="count" value="0">
</div>

Use this:
$newFileName = rtrim($file_name_insert, ',');
rtrim will remove the last unwanted , from the concatenated string.

Related

Get validation error message of array fields in laravel without displaying array key

I have an auto generated fields using jquery and my problem now is how to get error message without showing the index key. This is my code below:
#for($num = 0; $num < old('number', 1); $num++)
<input type="text" class="form-control guest_name" name="last_name[]" id="last_name" placeholder="lastname" value="{{ old('last_name', ['',''])[$num+1] }}">
#if ($errors->has('last_name' . ($num)))
<div class="form-group">
<p class="text-danger">{{ $errors->first('last_name' . ($num)) }}</p>
</div>
#endif
#endfor
This is my validation:
for($i=0; $i < count($this->request->get('last_name')); $i++){
$rules['last_name'.$i] = ['required'];
}
return $rules;
And now, the validation message is like this:
last name0 is required.
How can I just display it as last name is required.?
Thanks everyone for the inputs, I'm able to do it this way, someone might need it someday.
validation.php
<?php
$fields = ['last_name'];
$_30 = [];
$return =[
/*LANGUAGE LINES*/
'attributes' => [
'last_name' => 'Last Name',
];
];
foreach($fields as $field){
for($i = 0; $i<30; $i++) {
$return['attributes'][$field . $i] = $return['attributes'][$field];
}
}
return $return;

[Codeigniter]Multiple upload cant insert to database and not uploading to directory

How to upload multiple images with Codeigniter 4.x ?
I tried to loop the do_upload function in my model but it's not working, and I tried another code that I got from GitHub but still, none of it works.
This is my view:
<div class="section-body">
<h2 class="section-title">Entry Group Passanger</h2>
<div class="row">
<div class="col-md-12">
<form action="<?= base_url('passanger/addgroup') ?>" method="POST" enctype="multipart/form-data">
<?php for($i=1;$i<=$pax['pax'];$i++) : ?>
<h5>Passanger ke-<?= $i ?></h5>
<div class="form-row">
<div class="col-md-6">
<label for="fullname">Fullname</label>
<input type="text" class="form-control" name="name[]">
<?= form_error('name', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
<div class="col-md-6">
<label for="gender">Gender</label>
<select class="form-control select2-input" name="gender">
<option>-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<?= form_error('gender', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4 mt-2">
<label for="">Upload Passport</label>
<input type="file" name="upload_passport[]" id="input-file-now" class="dropify" />
</div>
</div>
this is my model :
public function addGroup()
{
$user = $this->db->get_where('user', ['username' => $this->session->userdata('username')])->row_array();
$pax = $this->getPaxById();
date_default_timezone_set('Asia/Jakarta');
$upload_image = $_FILES['upload_passport[]']['name'];
if ($upload_image) {
$config['upload_path'] = './assets/img/uploads/passport';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
for($i=0;$i<$pax['pax'];$i++) {
if ($this->upload->do_upload('upload_passport[$i]')) {
$new_image = $this->upload->data('file_name');
} else {
echo $this->upload->display_errors();
}
}
}
$name = $this->input->post("name[]");
$gender = $this->input->post("gender[]");
$birthdate = $this->input->post("birthdate[]");
$no_passport = $this->input->post("no_passport[]");
$expire_passport = $this->input->post("expire_passport[]");
$destination = $this->input->post("destination[]");
$date = $this->input->post("date[]");
$dp1 = "0";
$dp2 = "0";
$lunas = "0";
$type = "Group";
$status = "Not Complete";
$permission = "0";
$upload_passport = $new_image;
$upload_dp1 = "default.png";
$upload_dp2 = "default.png";
$date_created = date('d/m/Y H:i:s');
$data = [];
$jumlah = $pax['pax'];
for($x=0;$x<$jumlah;$x++) {
array_push($data, [
'name'=>$this->input->post("name[$x]"),
'id_user'=> $user['id_user'],
'gender'=>$this->input->post("gender[$x]"),
'birthdate'=>$this->input->post("birthdate[$x]"),
'no_passport'=> $this->input->post("no_passport[$x]"),
'expire_passport'=> $this->input->post("expire_passport[$x]"),
'destination'=> $this->input->post("destination[$x]"),
'date'=> $this->input->post("date[$x]"),
'dp1'=> $dp1,
'dp2'=> $dp2,
'lunas'=> $lunas,
'pax'=> $pax['pax'],
'type'=> $type,
'status'=> $status,
'permission'=> $permission,
'upload_passport'=> $new_image,
'upload_dp1'=> $upload_dp1,
'upload_dp2'=> $upload_dp2,
'date_created'=> $date_created
]);
var_dump($data); die;
}
$this->db->insert_batch("passanger", $data);
}
What I want to get is:
array('','','upload_image'), array('','','upload_image')
When insert it to database but when I do it the upload just gets output null and it's not even uploaded to my uploads directory. I would really appreciate it if you help me, I've been stuck on this for 3 days. Thank you.
for ($i=0; $i < sizeof($_FILES['image']['name']) ; $i++) {
$_FILES['file']['name'] = $_FILES['image']['name'][$i];
$_FILES['file']['type'] = $_FILES['image']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'[$i];
$_FILES['file']['error'] = $_FILES['image']['error'][$i];
$_FILES['file']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = PRODUCT_IMAGE_UPLOAD_PATH;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')){
$images[] = $this->upload->data('file_name');
}else {
echo $this->upload->display_errors();
}
}
Try this in Codeigniter 4
in your controller add this
$image_model = new App\Models\Images(); // Your model name that is load your model
if($imagefiles = $this->request->getFiles())
{
foreach($imagefiles['uploadImages'] as $img)
{
if ($img->isValid() && ! $img->hasMoved())
{
$image_name = $img->getRandomName(); // This is applicable if you want to change the name of the images
if($image_model->save_images($image_name))
{
$img->move(WRITEPATH.'uploads/images/ads', $image_name); // WRITEPATH.'uploads/images/ads' is the part you wish to save you file to
}
}
}
}
In your Model e.g Image model i have a method call save_images()as this
use Codeigniter\Model
class Images extends Model{
public function save_images($image = '')
{
// We set the column 'name' to be allow for data entry into the db. note this is mandatory for now.
// hope it will change in feature. 'name' is the column in database table where you will save the image name
// this command the CI4 db to select only the image column in the database table
$this->allowedFields = ['name'];
return $this->db->table('images')->insert(['name' => $image]);
// echo $sql = $this->db->getLastQuery();
}
}
Then in your html file input, do this
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="uploadImages[]" multiple>
</div>
</form>
I hope this will work for you

codeigniter upload 2 files (images and video ) in separate field

Hi i am new in codeigniter , I want to upload image and video in same form with different field. i did but it store either one. last one is stored like video.
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
And my controller is
public function videoupdate() {
$data['user_data'] = $this->session->userdata('user_logged_in');
if (($this->session->flashdata('success')))
$data['success'] = $this->session->flashdata('success');
else
$data['error'] = $this->session->flashdata('error');
if (!empty($data['user_data']['user_id'])) {
$title = $_POST['title'];
$description = htmlentities($_POST['description']);
$target_dir = './cms/uploads/blog/video3/';
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
} else {
$newfilename = "";
}
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
} else {
$videofilename = "";
}
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $newfilename);
move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $videofilename);
$createddate = date('Y-m-d H:i:s');
$ipaddress = $_SERVER['REMOTE_ADDR'];
$status = $this->microblog_model->insertBlogvideo($title, $description, $newfilename, $videofilename, $data['user_data']['user_id'], $createddate, $ipaddress);
I found your code for upload files is working fine. As I check it in separate php file:
<pre>
<?php
if(isset($_POST)){
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
try{
//upload image
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './uploads/' . $newfilename)){
echo "Image Uploaded<br/>";
}
}
//upload video
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
if(move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './uploads/' . $videofilename)){
echo "Video Uploaded<br/>";
}
}
}catch(Exception $e){
print_r($e);
}
}
?>
</pre>
<form method="post" enctype="multipart/form-data">
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
<input type="submit" name="submit">
</form>
You should check the size of video you are trying to upload and the maximum upload size allowed. I hope this will help. Because I checked it multiple times with many images and videos and found it is working fine.

Laravel checkbox implementation for updating database

I've been trying to make an attendance management system in Laravel.
In the attendance view,when a checkbox is checked ,the controller function is supposed to increment the appropriate database column.
I've been having some issues.Here's my code:
views:
<div class="container">
<!--<div class="row">-->
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Take Attendance</div>
<h4><center>Teacher: {{ auth()->user()->name}}</center></h4>
<div class="form-inline">
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
&nbsp&nbsp&nbsp&nbsp
{{ $sec->Name}}
</div>
<div class = "form-group">
<!--{{Form::checkbox('agree') }}-->
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="" />
</div>
#endforeach
</div>
<br>
<form action ="report_generate&<?php echo $name ?>" method = "post" enctype = "multipart/form-data" >
<!--<input type = "hidden" name = "_token" value = "{{{ csrf_token() }}}"/>-->
<div class = "form-group">
<input type="submit" value= "Submit">
<center>Report</center>
</div>
</form>
</div>
</div>
</div>
Controller(for submit button):
public function report_generate($tabu)
{
$year = DB::table('sub')->select('Year')-
>where('sub.Subject_Name','=',$tabu)->get();
$sub_id = DB::table('sub')->select('Subject_Id')-
>where('sub.Subject_Name','=',$tabu)->get();
ob_start();
echo $year;
$output=ob_get_contents();
ob_end_clean();
if ( $output=='[{"Year":1}]')
{
$req = "first";
}
elseif ( $output=='[{"Year":2}]')
{
$req = "second";
}
elseif ( $output=='[{"Year":3}]')
{
$req = "third";
}
elseif ( $output=='[{"Year":4}]')
{
$req = "fourth";
}
$final = DB::table($req)->get();
//dd($final);
//$columns = Schema::getColumnListing($req);
//dd($sub_id);
ob_start();
echo $sub_id;
//dd($sub_id);
$va=ob_get_clean();
$va = stripslashes($va);
$txt = rtrim($va,"}]");
$txt = ltrim($txt,"[{Subject_Id:");
$txt = ltrim($txt,"Subject_Id:");
$txt = explode(":",$txt);
$txt = str_replace('"','', $txt);
//dd($txt[1]);
$columns = Schema::getColumnListing($req);
//dd($columns);
//dd($txt);
foreach ($columns as $col)
{
//dd("Y");
if($col == $txt[1])
{
$got=DB::table($req)->select($col)->get();
//dd($got);
foreach($got as $g)
{
//want to increment that cell value
}
}
}
}
Looks like your checkboxs are outside of the form divs which is an issue. You also seem to be skipping over the Laravel features, for example having a Sub Model you can call on, or using the Request facade. Also not sure why you're using ob for those string comparisons (might actually want to look at Switch for that long elseif block) Lastly, you might want to to use a raw DB statement to do the increments within a SQL query
DB::statement("UPDATE " . $table . " set " . $column . " to " . $column . " + 1 WHERE id IN (" implode(', ', $ids) . ')")

Adding a file field to the manifest file

My plugin requires a user to upload a file.
The manifest field doesn't set the form enctype="multipart/form-data" so when a file is uploaded it gets lost.
Is there a way to change this?
form xml :
<field name="con_image" type="file" label="" description="" hint="Image"/>
default.php
<div class="controls">
<?php if (!empty($this->item->con_image) && file_exists(JPATH_SITE.'/images/contact_image/thumb_' . $this->item->con_image)) : ?>
<img src="<?php echo JRoute::_(JUri::root() . 'images/contact_image/thumb_' . $this->item->con_image, false);?>">
<?php endif; ?>
<input type="hidden" name="jform[con_image]" id="jform_image_hidden" value="<?php echo $this->item->con_image; ?>" />
<?php echo $this->form->renderField('con_image'); ?>
</div>
your view table file code for image upload:
$files = $app->input->files->get('jform', array(), 'raw');
$array = $app->input->get('jform', array(), 'ARRAY');
if (!empty($files['con_image']['name']))
{
// Deleting existing files
$oldFiles = PlansHelpersPlans::getFiles($this->id, $this->_tbl, 'con_image');
foreach ($oldFiles as $f)
{
$oldFile = JPATH_ROOT . '/images/contact_image/' . $f;
if (file_exists($oldFile))
{
unlink($oldFile);
}
}
$this->con_image = "";
$singleFile = $files['con_image'];
jimport('joomla.filesystem.file');
// Check if the server found any error.
$fileError = $singleFile['error'];
$message = '';
if ($fileError > 0 && $fileError != 4)
{
switch ($fileError)
{
case 1:
$message = JText::_('File size exceeds allowed by the server');
break;
case 2:
$message = JText::_('File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_('Partial upload error');
break;
}
if ($message != '')
{
$app->enqueueMessage($message, 'warning');
return false;
}
}
elseif ($fileError == 4)
{
if (isset($array['con_image']))
{
$this->con_image = $array['con_image'];
}
}
else
{
// Replace any special characters in the filename
jimport('joomla.filesystem.file');
$filename = JFile::stripExt($singleFile['name']);
$extension = JFile::getExt($singleFile['name']);
$filename = preg_replace("/[^A-Za-z0-9]/i", "-", $filename);
$filename = rand()."-".$filename . '.' . $extension;
$uploadPath = JPATH_ROOT . '/images/contact_image/' . $filename;
$fileTemp = $singleFile['tmp_name'];
if (!JFile::exists($uploadPath))
{
if (!JFile::upload($fileTemp, $uploadPath))
{
$app->enqueueMessage('Error moving file', 'warning');
return false;
}
}
//$this->con_image .= (!empty($this->con_image)) ? "," : "";
$this->con_image = $filename;
}
}else{
$this->con_image = $array['con_image'];
}
Still you have problem then check HERE
Download my simple component : https://github.com/erakashpatel/Important-notes/blob/master/com_helloworld.zip
OR
https://github.com/erakashpatel/Important-notes/blob/master/com_test.zip
I hope its works.Thanks in advance.
for xml :
Joomla File form field type in xml:
https://docs.joomla.org/File_form_field_type
<field name="myfilevalue" type="file" label="Enter some text" description="Choose an image from your computer with maximum 100KB" size="10" accept="image/*" />
OR
if your file field in html form then used :
<input type="file" name="jform[myfilevalue]" >
I hope its help,
else provide more description please

Resources