Hi everyone I need your help on how to split value from textarea and insert in a users table using laravel, I was able to get file content = "name | username | password", I need to split each value so I ca save it to a users table the file itself is save in a different table, should I put it in a different method or just specify my target table in the same as the file will be saved? Your help will be much appreciated.
UploadController:
public function store(Request $request){
$validator = Validator::make(
$request->all(),
['filename' => 'required|mimes:txt,jpeg,png,jpg,bmp|max:2048']
);
if ($validator->fails()) {
return back()->withErrors($validator->errors());
}
// if validation success
if ($file = $request->file('filename')) {
$filename = 'uploaded-here.' . $file->getClientOriginalExtension();
//stored in laravel local storage
$target_path = $file->storeAs('uploaded-here/', $filename);
if ($file->move($target_path, $filename)) {
// save file name in the database
$file = File::create(['filename' => $filename]);
return back()->with("success", "File uploaded successfully");
}
}
}
html code:
<div class="form-group" {{ $errors->has('filename') ? 'has-error' : '' }}>
<label for="filename"></label>
<input type="file" name="filename" id="filename" class="form-control">
<span class="text-danger"> {{ $errors->first('filename') }}</span>
<textarea id="editor" name="editor></textarea>
</div>
<button type="submit" class="btn btn-success btn-md"> Upload </button>
js
window.onload = function() {
var doc = document.getElementById('filename');
if (doc) {
doc.addEventListener('change', getFile);
}
}
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('editor'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
There is an error. Quotation closed sign is missing in name attribute of textarea.
<textarea id="editor" name="editor"></textarea>
You can split using JavaScipt's split() method. Like follwoing:
Say, you have the textarea value as your given format: name | email | password
as you have given example: example errol | errol.boneo13#gmail.com | password123.
Let's say, you have get the textarea value,
var textValue = document.getElementById('editor').value;
textValue = textValue .split(" | ");
var name = textValue [0];
var email = textValue [1];
var password = textValue [2];
Hope it helps....
EDIT::
As you wanted to do in laravel, you can do like following:
$textValue = $request->editor;
$textValue = explode(" | ", $textValue );
$name = $textValue [0];
$email = $textValue [1];
$password = $textValue [2];
Related
blade edit
<form action="/files" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<label for="dokumen">Dokumen Awal : ({{$aktivitas_list->dokumen}}) <br><i>Upload Ulang Dokumen</i></label>
<input type="file" id="dokumen" name="dokumen" accept=".pdf" class="form-control" value="{{$aktivitas_list->dokumen}}">
#if ($errors->has('dokumen'))
<span class="text-danger">{{ $errors->first('dokumen') }}</span>
#endif
controller store
$aktivitas_list = new Aktivitas;
$aktivitas_list->pt_id = $request->get('pt_id');
$aktivitas_list->nama_aktivitas = $request->get('nama_aktivitas');
$aktivitas_list->tgl_aktivitas = $request->get('tgl_aktivitas');
$aktivitas_list->tempat = $request->get('tempat');
$aktivitas_list->jenis_aktivitas = $request->get('jenis_aktivitas');
$aktivitas_list->dokumen = $request->file('dokumen');
$aktivitas_list->tenggat_waktu = $request->get('tenggat_waktu');
$aktivitas_list->deskripsi = $request->get('deskripsi');
$aktivitas_list->status = $request->get('status');
$aktivitas_list->user = $request->get('user');
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}
controller update
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
The problem is, if I don't select again the file when I update the data so the data is null. for example i just want to edit field nama aktivitas and not change the files. and another example i want to update all field. how can i get the files beside the browse button? how can i solve them? please guys help me
In Controller on update method
Make file as optional.
Check if request has file then make process of upload.
in view you can't set file input value for security reason.
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'nullable|mimes:pdf'//make file as optional
);
if($request->file('dokumen')){//check if file are exists on request
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
you can check if file existed then upload it and save file's new name in database and if file didn't exist just escape this field so old value remain in database.
if($request->hasFile()) {
}
See docs here
public function update(Request $request)
{
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'sometimes|mimes:pdf'
);
//Validation of request data
if($request->hasFile('dokumen') && $request->file('dokumen')->isValid()){
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
//Since your provided code snippet for update is truncated
// don't know how $aktivitas_list is instantiated
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}
I have a code where I want to save images using Vue and Laravel saves the route in the database
The Controller:
public function update(Request $request, $id){
$home = Home::findOrFail($id);
$home->background = $request->background;
$home->title = $request->title;
$home->subtitle = $request->subtitle;
$home->icon_go = $request->icon_go;
$fileName = $request->image;
$path = $_SERVER['DOCUMENT_ROOT'].'assets/images/'.$fileName;
$home->image = $path;
$home->update();
file_put_contents($path, $fileName);
return response()->json([
'status'=> 200,
'title' => 'Home Update',
'data' => $home,
]);
}
The input:
<v-col cols="12" sm="12" md="12">
<input type="file"
#change="getImage"
label="Imagen"
required
:class="{ 'is-invalid' : form.errors.has('image') }">
<has-error :form="form" field="image"></has-error>
</v-col>
Only I just put the input, the form is working fine
The function update:
update(){
//Update a resource
this.$Progress.start()
this.form.busy = true;
this.form.image = this.form.image.name
this.form.put('/api/v1/home/' + this.form.id)
.then(response => {
this.getHome()
if (this.form.successful) {
this.$Progress.finish()
this.updateNotify()
}else{
this.$Progress.fail()
this.$snotify.error('¡Ha ocurrido un error!', 'Error')
}
})
.catch(e => {
this.$Progress.fail()
console.log(e)
})
},
The problem may be in the controller but I cannot detect it.
I'd appreciate your help.
The only thing that does not work is that the image is not showing the content
The photo is saved in the folder public / assets / images This is how the image is saved in the folder
Try using the below code. Since $request->image won't give file object. Instead, we need to use file() helpr.
public function update(Request $request, $id){
$home = Home::findOrFail($id);
$home->background = $request->background;
$home->title = $request->title;
$home->subtitle = $request->subtitle;
$home->icon_go = $request->icon_go;
$file = $request->file('image'); //gets the image file
$path = $_SERVER['DOCUMENT_ROOT'].'assets/images/';
$home->image = $path.$file->getClientOriginalName();
$home->update();
$file->move($path, $file->getClientOriginalName()); //stores in location
return response()->json([
'status'=> 200,
'title' => 'Home Update',
'data' => $home,
]);
}
I have upload form which user can add posts with tags. When I enter tag in the input field I've got this error
FatalThrowableError in BelongsToMany.php line 866:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatSyncList() must be of the type array, null given, called in
This is what I have in Tag model
public function itemTags()
{
return $this->belongsToMany('App\Item', 'item_tag');
}
In my Item model
public function taggs()
{
return $this->belongsToMany('App\Tag', 'item_tag');
}
The field in my view
<div class="form-group">
{!! Form::label('inputTags', 'Tags', array('class'=> 'col-sm-2 control-label')) !!}
{!! Form::text('tags', null, ['class'=>'form-control', 'id'=>'inputTags']) !!}
</div>
And the controller
public function store( ItemRequest $request )
{
$image = $request->file('image');
$filename=null;
if( $image && $image->isValid()){
$extension = $image->getClientOriginalExtension();
$uploadPath = public_path(). '/uploads';
$filename = rand(111,999). '.'. $extension;
$image->move($uploadPath, $filename);
}
$item = new Item;
$item->title = $request['title'];
$item->category_id = $request['category_id'];
$item->description = $request['description'];
$item->user_id = Auth::user()->id;
$item->url = $request['url'];
$item->image = $filename;
if($item->save()){
if(!is_null($filename)) {
$item_image = new Item_Images;
$item_image->image = $filename;
$item_image->item_id = $item->id;
$item_image->published = 1;
$item_image->save();
}
$request->session()->flash('alert-success','Item added successfully.');
}else
$request->session()->flash('alert-error','Can not add item now. Plese tyr again!!.');
$item->taggs()->sync($request->tags);
return redirect()->route('frontend.user.myitems');
}
The error is on this line
$item->taggs()->sync($request->tags);
What is the problem here?
Maybe your request of tag value $request->tags get empty, Try to call sync like:
$syncTagData = array();
//Passing empty array if tag request is empty...
if(!empty($request->tags)){
$syncTagData= $request->tags;
}
$item->taggs()->sync($syncTagData);
Update
If your request $request->tags not the type array, try below code:
$syncTagData = array();
//Passing empty array if tag request is empty...
if(!empty($request->tags)){
array_push($syncTagData, $request->tags);
}
Today I got same error in many to many relationship between a plot and features.
Reason behind this was user wasn't selecting the features and null was passing to sync()
$plot->featureset()->sync($request->features);
Solution:
$feature_set = ($request->features) != null) ? $request->features : [];
$plot->featureset()->sync($feature_set);
Regards
Try this it works for my project.
if (isset($request->tags)) {
$intern->tags()->sync($request->input('tags'), false);
} else {
$intern->tags()->sync(array());
}
I want letting user add dynamic inputs and save those values in the database. But with this code only one value save to the database. How can I save all values to the database entered by user
this is my view to add dynamic inputs
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('</br><div><input class="input form-control"" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<div class="input_fields_wrap">
<div class="form-group">
<button type="button" class="btn btn-success add_field_button">Add More Fields</button>
</div>
<div>
<input class="input form-control" name="mytext[]">
</div>
</div>
This is my controller to save those dynamic inputs in the database
function error(){
if ($this->input->post('mytext')) {
$attain = $this->input->post('mytext', true);
foreach ($attain as $i => $a) { // need index to match other properties
$data2 = array(
'mytext' => $a,
'projectname' => $this->input->post('projectname'),
);
$this->db->insert('projectem', $data2);
redirect('Select_ctrl2/ModalAddEmployeesProject');
}
}
}
function error(){
if ($this->input->post('mytext')) {
$attain = $this->input->post('mytext', true);
$data2=array(); //<-initialize
foreach ($attain as $i => $a) { // need index to match other properties
//append array
$data2[] = array(
'mytext' => $a,
'projectname'=> $this->input->post('projectname'),
);
//for multiple entry in same table
$this->db->insert_batch('projectem', $data2);
redirect('Select_ctrl2/ModalAddEmployeesProject');
}
}
}
My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.
If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}