File does not upload when on mobile, but works on desktop - laravel

This is my blade code:
<form action="{{ route('picture.store') }}" method="post" enctype="multipart/form-data">
#csrf
<input type="file" name="fotoRemolque" id="fotoRemolque"
placeholder="Tomar Foto de Remolque" class="inputsLogin"
multiple capture="camera" accept="image/*">
#error('fotoRemolque')
<small class=" text-danger">{{$message}}</small>
#enderror
<br>
<div class="col-12 text-center margen">
<h3 >Numero de Remolque:</h3>
<input type="text" name="remolque" id="result" class="inputRemolqueContenedor" readonly>
#error('remolque')
<small class=" text-danger"> {{$message}}</small>
#enderror
</div>
<input type="submit" value="EnviarImagen" id="enviarImg" class="btnEnviarImagen">
</form>
And here is my controller:
$request->validate([
'fotoRemolque' => 'required|image',
'remolque' => 'required|string'
]);
$remolque = $request->input('remolque');
$nombre = Auth::user()->username;
$terminal = Auth::user()->terminal;
$fecha = Carbon::now();
$pictureName = $nombre.$terminal.$remolque.$fecha.".png";
$images = $request->file('fotoRemolque')->store('public/imagesTrailers');
$url = Storage::url($images);
$url = Str::after( $url, 'http://localhost');
$picture = new Picture();
$picture->username = $nombre;
$picture->terminal = $terminal;
$picture->trailer = $remolque;
$picture->date = $fecha;
$picture->image_url = $url;
$picture->save();
The problem happens only on the mobile view, it doesn't upload the file, here is the problem:
I have the app in windows server 2012

Related

Check if at least one input has value with laravel controller

I have a simple form where the user should be able to only fill the inputs he wants but if the form hasn't at least one input filled, it should return a error message saying that the form can't be empty if he clicks the submit button.
Here's my form:
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
#endif
</center>
<form action="{{ route('send-update') }}" method="POST" enctype="multipart/form-data"> #csrf
<label>Nome do projeto:</label>
<div class="input-group mb-3"><br>
<input type="text" class="form-control" name="project_name" aria-label="Username" aria-describedby="basic-addon1">
</div>
#error('project_name')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Descrição:</label>
<div class="input-group mb-3"><br>
<textarea class="form-control" name="desc" aria-label="With textarea"></textarea>
</div>
#error('desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem alguma imagem que queira mudar/inserir?</label>
<div class="input-group mb-3">
<input type="file" name="img" accept="image/*" class="form-control" id="inputGroupFile01">
</div>
#error('img')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<div class="input-group mb-3">
<input type="text" class="form-control" name="img_desc" placeholder="Diga-nos onde pretende mudar/adicionar">
</div>
#error('img_desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem mais informações? Insira um arquivo .txt, docx ou pdf</label>
<div class="input-group mb-3">
<input type="file" name="ficheiro" accept=".xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf" class="form-control" id="inputGroupFile01">
</div>
#error('ficheiro')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<input type="hidden" name="id" value="{{ request('id') }}">
<center> <button type="submit" class="btn btn-secondary ">Fazer pedido de atualização</button></center><br>
</form>
And here's the controller:
public function sendUpdate(Request $request){
$id = $request['id'];
$order = Order::where('id', $id)->first();
$validator = Validator::make($request->all(), [
'project_name' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'img' => ['nullable', 'image', 'mimes:jpeg,png,jpg,svg', 'max:1024'],
'img_desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'ficheiro' => ['nullable', 'csv,txt,xlx,xls,pdf', 'max:2048'],
]);
if (request()->hasFile('ficheiro')){
if (request()->file('ficheiro')->isValid())
{
$fileName = $request->file('ficheiro')->getClientOriginalName();
$path = $request->file('ficheiro')->storeAs('files', $fileName, 'public');
}}
if (request()->hasFile('img')){
if (request()->file('img')->isValid())
{
$imageName = $request->file('img')->getClientOriginalName();
$pathImg = $request->file('img')->storeAs('files', $imageName, 'public');
}}
Update::create([
'customer_name' => $order->customer_name,
'customer_email' => $order->email,
'project_name' => $order->project_name,
'project_new_name' => $request['project_name'],
'description' => $request['desc'],
'image' => $pathImg ?? '',
'image_desc' => $request['img_desc'],
'ficheiro' => $path ?? '',
]);
return back()->with('success','Obrigado! Entraremos em contacto consigo em breve!');
}
I have no idea how to check if all inputs are empty in the controller . I've already tried this below, but it doesn't work. It keeps sending the form anyway.
if(count($request->all()) < 0) {
return dd('request all input empty.');
}
You can do it this way.
if(empty(array_filter($request->all()))){
//All fields are empty.
}

Update image in laravel won't work

I'm trying to update image in my laravel project but it won't save the image, I'm using intervention package
this is the result i use dd
Controller:
public function update(Request $request, $id)
{
//
$this->validate($request, [
'student_name'=>'required|max:50',
'lead_status'=>'required|max:50',
'lead_source'=>'required|max:50',
'avatar' =>'image',
]);
$leads = Lead::findOrFail($id);
$leads->student_name = $request->student_name;
$leads->student_nric = $request->student_nric;
$leads->gender = $request->gender;
$leads->religion = $request->religion;
$leads->race = $request->race;
$leads->date_of_birth = $request->date_of_birth;
$leads->Address = $request->Address;
$leads->last_school_attended= $request->last_school_attended;
$leads->last_grade_completed = $request->last_grade_completed;
$leads->grade_appliying = $request->grade_appliying;
if($request->hasFile('avatar')){
$image=$request->file('avatar');
$filename=time() . '.' . $image->getClientOriginalExtension();
$location=public_path('images/' .$filename);
Image::make($image)->resize(300, 300)->save($location);
$leads->image=$filename;
$leads->save();
}
else{
$leads->save();
session()->flash('notif','Application Saved Successfully');
return view('leads.edit')->with('leads', $leads);
}
}
Edit.Blade View
<div class="row">
<div class="col-sm-4 form-group">
<img src="/uploads/avatars/{{$leads->image}}" style="width:150px;height:150px;border-radius:50px;">
<form enctype="multipart/form-data" action="{{route('leads.update', $leads->id)}}" method="POST" >
{{ csrf_field() }}
{{ method_field('PUT') }}
<label> Upload Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<div class="col-sm-12">
<h4 text-muted>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input class="form-control" style="text-transform: uppercase;" type="text" name="student_name" value="{{$leads->student_name}}" placeholder="Enter FULLNAME.." autocomplete="off">
</div>
Note: i will always end up null value on my image please point me to a correct tutorial if u have..
......................................................................................................................................
Add a hidden input type with your database variable in your edit blade
and put the value of your hidden input name in else condition to save.
<input type="hidden" name="old_image_name"
value="#if(isset($admin_details)){{$admin_details->image}} #endif"/>

Multiple images update Laravel deleted

Hi there if anyone can help me, I have the code for updating images and it works fine when I upload another image, and I do not touch the others for example the first image I change and I upload an image the three others I do not touch and I click submit edit button and when I go back to the view of edit I can only see the one photo that I changed the three others are gone..
this is the blade:
<form class="form-horizontal" method="POST"
action="{{ action('website\questions\MatchLinesWithPhotosController#updateQuestion', ['id' => $question->id]) }}"
enctype="multipart/form-data">
{{ csrf_field() }}
#include('website.questions.general-update-header')
<div class="row">
<div class="col-lg-5">
<label style="padding-left: 10px">
<h4 class="box-title">#lang('general.options_for_answers'):</h4>
<em class="text-caption" id="caption-question-type"> *#lang('general.chose_correct_multiple_choice_photo')</em>
</label>
</div>
</div>
<div class="optionsFormMatchlinePhotos">
#for($i=0; $i<=(count($answers->where('deleted', 0))/2)-1; $i++)
<div class="col-md-6" id="option{{ $i }}">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<?php $option = $answers->where('deleted', 0)->where('order', $i)->where('is_key', 1)->first(); ?>
<div class="info-box answer-with-photo-option">
<img src="{{url('/')}}/images/answers/{{ $option->id }}/medium/{{ $option->image_path }}" class="answer-image-create" id="image{{ $i }}">
</div> #if($option)<input onchange="readURL(this, {{ $i }});" type="file" name="image{{ $i }}" id="<?php echo 'answer_file'.$i;?>" style="
margin-top: -19%;
padding-bottom: 9%;
" />
#endif
</div>
</div>
<div class="row">
<div class="form-group {{ $errors->has('options.'.$i) ? ' has-error': '' }}">
<div class="col-md-12">
<div class="col-md-3" style="width: 20%;">
{{-- <input type="text" name="options[{{ $i }}]" value="{{ $i }}" style="display :none" /> --}}
</div>
<input type="text" name="matchanswer[{{ $i }}]" value="{{ $i }}" style="display :none" />
<?php $match = $answers->where('deleted', 0)->where('order', $i)->where('is_key', 0)->first(); ?>
<div class="col-md-5">
#if($match)
<input type="text" name="match{{ $i }}" value="{{$match->text}}"
class="form-control" placeholder="#lang('general.match') {{ $i + 1}}">
#else
<input type="text" name="match{{ $i }}" value=""
class="form-control" placeholder="#lang('general.match') {{ $i + 1}}">
#endif
#if($errors->has('match.'.$i))
<div class="col-md-12"></div>
<span class="help-block">
<strong>{{ $errors->first('match.'.$i) }}</strong>
</span>
#endif
</div>
<div class="col-md-4">
<button type="button" value="{{ $i }}" class="btn btn-flat btn-default btn-sm" id="delete_option" title="#lang('buttons.remove_option')">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
</div>
#endfor
</div>
and here is the edit controller:
public function editQuestionForm($id){
$question = Question::findOrFail($id);
$answers = MatchLineAnswer::where('question_id', $id)->get();
return view('website.questions.partials.matchlineswithphotos.edit-matchlineswithphotos',compact('question', 'answers'));
return session('message');
}
public function updateQuestion(MatchLinesWithPhotosFormRequest $request, $id){
$QuestionController = new QuestionController();
$QuestionController->UpdateQuestion($request, $id);
MatchLineAnswer::where('question_id', $id)->update(['deleted' => 1]);
$to_delete_answers = MatchLineAnswer::select('id')->where('question_id', $id)->get();
MatchLineAnswer::where('question_id', $id)->update(['deleted' => 1]);
$imgController = new ImagesController();
$element = 'answers';
foreach($to_delete_answers as $deleted_answer){
$imgController->deleteImage($element, $deleted_answer->id);
}
foreach ($request['matchanswer'] as $key => $option){
$answer_create = MatchLineAnswer::create([
'question_id' => $id,
'order' => $option,
'is_key' => 1
]);
$img = $request->file('image'. $option);
$create_answer_id = $answer_create->id;
$imgController->uploadAnswerImage($img, $element, $create_answer_id);
$answer_update = MatchLineAnswer::where('id', $create_answer_id)->update(['image_path'=> $imgController->getUniqueNameAttribute()]);
MatchLineAnswer::create([
'question_id' => $id,
'order' => $option,
'text' => strip_tags($request['match'.$option]),
'is_key' => 0
]);
}
$test_id = Question::where('id', $id)->first();
session()->flash('message', 'Question successfully updated');
return redirect()->action('website\tests\CompleteTestController#showAllTestInfo', ['test_id' => $test_id->test_id]);
}

Image uploading using codeigniter file uploading class

This is not a how to upload image question . I have almost successfully managed to add a image upload function into my add client function . It works well when i try to upload a valid file .. but when i select a invalid file or larger file then it shows undefined variable upload_data and codeigniter database error where img_path is NULL it says Column 'img_path' cannot be null. why this function isn't working $this->upload->display_errors(); . The validation errors are showing nicely but no file validation error showing up.
I am using Codeigniter and hmvc
here is my controller
<?php
class Clients extends MX_Controller{
function __construct(){
parent::__construct();
$this->load->model('mdl_clients');
}
function add(){
$data['success'] = null;
$data['errors']= null;
if($_POST){
$config_arr = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '2048',
'max_width' => '1024',
'max_height' => '768',
'encrypt_name' => true,
);
$this->load->library('upload', $config_arr);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors(); // this isn't working
} else {
$upload_data = $this->upload->data();
}
$config=array(
array(
'field'=>'firstName',
'label'=>'First Name',
'rules'=>'required|max_length[15]|min_length[3]'
),
array(
'field'=>'city',
'label'=>'City',
'rules'=>'required'
),
array(
'field'=>'mobile_phone',
'label'=>'Mobile Number',
'rules'=>'required'
),
array(
'field'=>'email',
'label'=>'Email',
'rules'=>'required|is_unique[clients.email]|valid_email'
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}
$data['title'] = 'Add Client Database';
$data['main_content'] = 'clients/add';
echo Modules::run('templates/admin', $data);
}
and my view file .. add.php
<? if($success==1) {?>
<div class="alert alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
Data Has been Updated !
</div>
<? } ?>
<?php if($errors) { ?>
<div class="alert alert-error" >
<a class="close" data-dismiss="alert" href="#">×</a>
<?=$errors?>
</div>
<? } ?>
<?php $attributes = array('class' => 'form-horizontal');
echo form_open_multipart('clients/add', $attributes); ?>
<fieldset>
<!-- Address form -->
<h2>Client Information</h2>
<hr />
All Fields Marked with <span style="color: red;">*</span> is necessary .
<hr />
<!-- Upload input-->
<div class="control-group">
<label class="control-label">Upload<span style="color: red;">*</span></label>
<div class="controls">
<input name="userfile" name="userfile" type="file"
class="input-xlarge">
<p class="help-block"></p>
</div>
</div>
<!-- firstName input-->
<div class="control-group">
<label class="control-label">First Name<span style="color: red;">*</span></label>
<div class="controls">
<input id="firstName" name="firstName" type="text" placeholder="First Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Email input-->
<div class="control-group">
<label class="control-label">E-Mail<span style="color: red;">*</span></label>
<div class="controls">
<input id="email" name="email" type="text" placeholder="A Valid Email Address"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- City input-->
<div class="control-group">
<label class="control-label">City<span style="color: red;">*</span></label>
<div class="controls">
<input id="city" name="city" type="text" placeholder="City Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
<!-- Mobile input-->
<div class="control-group">
<label class="control-label">Mobile Number<span style="color: red;">*</span></label>
<div class="controls">
<input id="mobile_phone" name="mobile_phone" type="text" placeholder="Current Mobile Phone Number"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Add to Database</button>
</div>
</div>
</fieldset>
</form>
Assuming an input element of:
<input type="file" name="image" id="image">
Change the following line:
!$this->upload->do_upload()
to:
!$this->upload->do_upload('image')
Please let me know if you face any problem.
UPDATE
If you want to send it to the template then do something like this:
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg',$error['error']);
redirect('controller_name/function_name','refresh');
}
Let me know if this works for you.
While doing the form validation you are not taking into consideration if there were upload errors or not. You should check if there were upload errors or not than proceed with the form validation
if($data['errors'] != '')
{
//do something, probably redirect back to the view and show the errors
}
else
{
if($this->form_validation->run() == FALSE)
{
$data['errors'] = validation_errors();
}
else
{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}

upload image got error in codeigniter

what im trying to do is Im trying to upload an image to database but I dont know what is the reason why I've got an error like
Message: Undefined index: userfile
Message: Undefined variable: images
in my view. as you can see the name of the input file set as an array same as other tutorial
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstName" placeholder="First Name" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile[]" id="file" class="form-control">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal
in my controller.
public function image()
{
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']); //this is line that has an error, the Message: Undefined index: userfile
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images); // the line that has an error, Message: Undefined variable: images
return $fileName;
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
'image' => $this->input->post($this->image()),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
// 'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$this->person->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
I want to insert that image name to my database but that errors block me to do that... need help.
In your Ajax Request Please add
$("#form").submit(function(e){
e.preventDefault();
var fd = new FormData();
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
data: formData,
So on....
//ajax close
});
And DOnt Forgot to use
enctype="multipart/form-data"
On form tag...And You will be fine
For Undefined variable: images
Please put
$images = array();// just before for loop.
$cpt = count($_FILES['userfile']);

Resources