I need to store my images in the database in one column dynamically I have no idea how to do it please help me. thank you in advance here is my view controller and model. Here is an image, Below there are an array that on Choose File Button. I want to store them into the database in a column how to do that?
My Database Table name is InflightMagazine
My VIEW code
{!! Form::open(['action'=>'Admin\InflightMagazines#store', 'method' => 'POST','enctype'=>'multipart/form-data']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr class="form-row">
<td> <b>{{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}}</b><br>
{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}
{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle add', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
AJAX / JQuery Code
<script>
$(document).ready(function() {
var len = $('.form-row').length;
$(document).on('click', '.add', function() {
$('#dynamic_field').append('<tr class="form-row" data-id="'+len+'"><td> {{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}} <br> {{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }} {{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}</td><td><button type="button" name="remove" class="btn btn-danger fa fa-minus-circle btn_remove_all"></button></td></tr>');
});
$(document).on('click', '.submit', function() {
$.ajax({
method: "POST",
data: $('#add_name').serialize(),
success: function(data) {
alert(data);
$('#add_name')[0].reset();
}
});
});
$(document).on('click', '.addFile', function() {
var id = $(this).closest('.form-row').data('id');
var elem = '<tr class="'+id+'"><td>{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}<button type="button" name="remove" class="btn btn-danger btn_remove fa fa-minus-circle"></button></td></tr>';
$(elem).insertAfter($(this).closest('tr'));
});
$(document).on('click', '.btn_remove, .btn_remove_all', function() {
if($(this).hasClass('btn_remove_all')){
var id = $(this).closest('.form-row').data('id');
$('tr.'+id).remove();
}
$(this).closest('tr').remove();
});
});
</script>
Controller Storing Function code
public function store(Request $request){
$this->validate($request, [
'inflightmagz_date' => 'required',
'infightmagazine_pdf' => 'required'
]);
if ($request->has('infightmagazine_pdf')){
//Handle File Upload
$inflightmags = [];
foreach ($request->file('infightmagazine_pdf') as $key => $file){
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
}
$fileNameToStore = serialize($inflightmags);
}
}
I think what you are looking for is attribute casting to array
https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
this will allow you to save an array of file locations to a single field in the DB and retrieve them as an array
I would remove the serialise on the $fileNamesToStore
Hope this helps
Related
I am using Laravel 5. In this application, the staff name can be added and deleted dynamically. For creating new records, all functions run smoothly. However, I have some difficulties in updating the records. In 'edit' page, the staff names created are displayed and can be changed. These names can be updated. But, I put add button and delete button to enable user to add new staff name or delete existing staff name.
My function just can update existing record in database. But the new added staff name not inserted in database. This is my function to update in controller.
public function update(Request $request, $id)
{
$demo = Demo::findOrFail($id);
$demo->tajuk_demo = $request->tajuk_demo;
$demo->syarikat_id = $request->nama_syarikat;
$demo->peralatan_sistem = $request->peralatan_sistem;
$demo->tarikhmasa = $request->tarikhmasa;
$demo->tarikhmasa_tamat = $request->tarikhmasa_tamat;
$demo->tempat_demo = $request->tempat_demo;
$demo->ulasan_demo = $request->ulasan_demo;
$demo->komen_demo = $request->komen_demo;
$demo->update();
$pegawai = $request->all();
// $rekod_id = $pegawai['rekod_id'];
$itemRegistrationID = $pegawai['nama'];
$OperasiID = $pegawai['pangkat'];
$SectionID = $pegawai['bahagian'];
$pegawai_semasa = Pegawai::where('rekod_id', '=', Input::get('rekod_id'))->exists();
$peg_hadir = Pegawai::where('demo_id', '=', $id)
->get();
// Update the existing record
foreach($peg_hadir as $peg){
$key = array_search($peg->rekod_id, $pegawai['rekod_id']);
$peg->itemRegistrationID = $itemRegistrationID[$key];
$peg->OperasiID = $OperasiID[$key];
$peg->SectionID = $SectionID[$key];
$peg->save();
}
if (is_null($pegawai_semasa))
{
// Insert new record into database
$count = count(Input::get('nama'));
// get data
$itemRegistrationID = Input::get('nama');
$OperasiID = Input::get('pangkat');
$SectionID = Input::get('bahagian');
//loop through and save data
for($i = 0; $i < $count; ++$i) {
$pegawai = new Pegawai;
$pegawai->demo_id = $id;
$pegawai->itemRegistrationID = $itemRegistrationID[$i];
$pegawai->OperasiID = $OperasiID[$i];
$pegawai->SectionID = $SectionID[$i];
$pegawai->save();
}
}
else
{
return redirect('demo');
}
}
This is the code in view blade for edit page:
<div class="form-group">
<div class="row">
<input type="button" class="add-row" value="Add">
<button type="button" class="delete-row">Delete</button>
</div>
</div>
<!--mula table -->
<div class="form-group">
<div class="row">
<div class="col-lg-10">
<table class="table table-striped table-bordered" id="pegawaihadir_table" >
<thead>
<tr>
<td class="text-center col-lg-1"><strong>Pilih</strong></td>
<td class="text-center col-lg-1"><strong>Pangkat</strong></td>
<td class="text-center col-lg-3"><strong>Nama</strong></td>
<td class="text-center col-lg-2"><strong>No Badan</strong></td>
<td class="text-center col-lg-2"><strong>Seksyen</strong></td>
<td class="text-center col-lg-2"><strong>No Tel</strong></td>
<td class="text-center col-lg-2"><strong>Ext</strong></td>
</tr>
</thead>
<tbody>
#foreach($PegawaiHadir as $value)
<tr>
<td><input type="checkbox" name="rekod" style="width:20px">
{!! Form::hidden('rekod_id[]', $value['rekod_id'], ['class' => 'form-control']) !!}
</td>
<td class="text-center">{{ Form::text('pangkat[]', $value['OperasiID'], ['class' => 'form-control pangkat', 'readonly' => 'true']) }}</td>
<td>
{{ Form::select('nama[]', $pegawai, $value['itemRegistrationID'], ['class' => 'form-control nama', 'required' => '']) }}
</td>
<td class="text-center">{{ Form::text('no[]', $value['Nobadan'], ['class' => 'form-control no', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('bahagian[]', $value['SectionID'], ['class' => 'form-control bahagian', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('telefon[]', $value['notelttp'], ['class' => 'form-control telefon', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('ext[]', $value['ext'], ['class' => 'form-control ext', 'readonly' => 'true']) }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
For dynamic fields, I am using js code to add and delete the record displayed in the page.
<script>
count=1;
$(document).ready(function(){
$(".add-row").click(function(){
var markup = '<tr><td><input type="checkbox" name="rekod" style="width:20px"></td>';
markup += '<td><input type="text" class="form-control pangkat" name="pangkat[]" style="width:100px" readonly></td>';
markup += '<td><select class="form-control select2 nama" name="nama[]" style="width:300px"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
markup += '<td><input type="text" class="form-control no" name="no[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control bahagian" name="bahagian[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control telefon" name="telefon[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control ext" name="ext[]" style="width:100px" readonly></td></tr>';
$("table tbody").append(markup);
count++;
});
$(document).on('change', 'select.form-control.nama', function() {
var PegID = jQuery(this).val();
var row = $(this);
// alert(PegID);
if(PegID)
{
jQuery.ajax({
context: this,
url : 'get_pegawai/'+PegID,
type : "GET",
dataType : "json",
success:function(data)
{
console.log(data);
$(this).closest('tr').find('td .form-control.pangkat').val(data.operasiname);
$(this).closest('tr').find('td .form-control.no').val(data.Nobadan);
$(this).closest('tr').find('td .form-control.bahagian').val(data.sectionname);
$(this).closest('tr').find('td .form-control.telefon').val(data.notelttp);
$(this).closest('tr').find('td .form-control.ext').val(data.ext);
}
});
}
else
{
$(this).closest('tr').find('td .form-control.pangkat').empty();
$(this).closest('tr').find('td .form-control.no').empty();
$(this).closest('tr').find('td .form-control.bahagian').empty();
$(this).closest('tr').find('td .form-control.telefon').empty();
$(this).closest('tr').find('td .form-control.ext').empty();
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="rekod"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
I also doesn't know how to identify the selected staff name to be deleted from existing record in database. I am providing a complete code to ease anyone who want to help to understand better. Thank you.
Make this ajax call into an IIFE
$(function(){
$(document).on('change', 'select.form-control.nama', function() {
var PegID = jQuery(this).val();
var row = $(this);
// alert(PegID);
if(PegID)
{
jQuery.ajax({
context: this,
url : 'get_pegawai/'+PegID,
type : "GET",
dataType : "json",
success:function(data)
{
console.log(data);
$(this).closest('tr').find('td .form-control.pangkat').val(data.operasiname);
$(this).closest('tr').find('td .form-control.no').val(data.Nobadan);
$(this).closest('tr').find('td .form-control.bahagian').val(data.sectionname);
$(this).closest('tr').find('td .form-control.telefon').val(data.notelttp);
$(this).closest('tr').find('td .form-control.ext').val(data.ext);
}
});
}
else
{
$(this).closest('tr').find('td .form-control.pangkat').empty();
$(this).closest('tr').find('td .form-control.no').empty();
$(this).closest('tr').find('td .form-control.bahagian').empty();
$(this).closest('tr').find('td .form-control.telefon').empty();
$(this).closest('tr').find('td .form-control.ext').empty();
}
});
});
And also change update() method to save() method in your controller.
I want to upload an Image and a Video, here is my logic but it seems does not work It only uploads one image. how can i upload 2 separate data. Please Guide me I am new to Laravel thank you
Here is the View which has a form I've used in Form Collectives
Here is where the arrays have been called
My View
{!! Form::open(['action'=>'Admin\PaxSafetyController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{ Form::file('paxsafety_image[]') }} <strong>Upload Image</strong>
<br><br>
{{ Form::file('paxsafety_video[]') }} <strong>Upload Video</strong>
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
My Controller
public function create()
{
$this->validate($request, [
'paxsafety_image' => 'required',
'paxsafety_video' => 'required'
]);
if ($request->has('paxsafety_image'))
{
//Handle File Upload
$paxSafety = [];
foreach ($request->file('paxsafety_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/paxsafety_folder',$fileNameToStore);
array_push($paxSafety, $fileNameToStore);
}
$fileNameToStore = serialize($paxSafety);
}
foreach ($paxSafety as $key => $value) {
$paxSafetyContent = new PaxSafety;
$paxSafetyContent->paxsafety_image = $value;
$paxSafetyContent->save();
}
return redirect('/admin/airlineplus/inflightmagazines/create')->with('success', 'Inflight Magazine Content Inserted');
}
I have a problem here. I am developing my web application and I want it to connect to my API through ajax. I am trying to send an image to my api through ajax from my form in the client side, which is the web.
So, here's my form in the client side..
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
{{ csrf_field() }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
Here's my ajax, still in the client side
<script type="text/javascript">
$(".add").click(function() {
$.ajax({
url: 'http://127.0.0.1/identificare_api/public/api/plants',
data: new FormData($("#addplant")[0]),
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
</script>
EDIT: and in my api, I just have this one
return json_encode($request->file('image_url'));
What am I missing here? Did I missed something?
UPDATE: I tried to apply the answer of #bfcior but when I try to console.log(base64img), it will return this very long string and it's longer than you expected.
click for image
I'm not entirely sure if this is the issue but aren't you supposed to be using a button instead of a submit? I'd imagine using a submit is preventing the ajax from working because the form is being submitted to the server for processing.
EDIT: What happens when you click the submit button? Telling us will help stackoverflow users diagnose the problem.
You handle the file by using:
$request->file('image_url');
https://laravel.com/docs/5.3/requests#files
Another approach is to convert img into base64 and pass it as a param. Then in your controller/route you can decode the base64 and save to a file (if is needed).
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
var base64img = null;
$(document).ready(function() {
$('#image').change(function(){
var file = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
base64img = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
$(".add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'http://127.0.0.1:8000/identificare_api/public/api/plants',
data: $("#addplant").serialize() + '&image_url=' + base64img,
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
});
</script>
and route
Route::post('identificare_api/public/api/plants', function (Request $request) {
return json_encode($request->all());
});
i develop web application with laravel 5.2 , i try to send an array with ajax to my controller , the request sent but after that i saw the error :405 method not allowed , i searched many times but this problem didn't solve :
my ajax code is :
// send array of stream checkbox to controller
$('#json-btn').click(function () {
var input = $("form input:checkbox");
var stream = [];
$.each($(input), function(){
stream.push($(this).val());
});
var jstream = JSON.stringify(stream);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/ajaxGet/',
type: 'POST',
data: {_token: CSRF_TOKEN , jstream:jstream},
dataType: 'JSON',
success: function (data) {
alert(data);
}
});
});
my route is :
Route::post('ajaxGet', 'ajaxController#getRequest');
my controller is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class ajaxController extends Controller
{
public function getRequest(Request $request)
{
echo $request['jstream'];
}
}
and finally this is my form :
{!! Form::open(array('id' => 'trailer-form')) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<table dir="rtl">
<thead>
<tr>
<th>quality</th>
<th>link</th>
<th>steram</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{!! Form::select('quality[]', array('noQuality'=>'select...','64p'=>'64p','144p'=>'144p','240p'=>'240p','360p'=>'360p','480p'=>'480p','720p'=>'720p', '1080p'=>'1080p'), null , ['class'=> 'form-control lns' , 'id' => 'quality-input']) !!}
</td>
<td>
{!! Form::text('downLoadLink[]',null,['class' => 'form-control ln' , 'id' => 'down-input']) !!}
</td>
<td>
{!! Form::checkbox('stream[]','false',null,['class' => 'form-control' , 'id' => 'streamCheck' , 'onchange' => 'createAlerts(this)']) !!}
</td>
<td>
<button class="btn btn-success btn-add" type="button">
<i class="glyphicon glyphicon-plus gs"></i>
</button>
</td>
</tr>
</tbody>
</table>
{!! Form::submit('json create',['class' => 'btn btn-success' , 'id' => 'json-btn']) !!}
{!! Form::close() !!}
please help me to solve this problem thank you so very much :)
I have written a code that sends email to selected people using check-box, now I have to add select all and clear all button so that all the check-boxes should get selected/dis-selected.
Here is my code:
My controller:
public function display(){
$data = Input::get('agree');
$count = count ($data);
$this->contact( $data );
return view('clientinfo.display', compact('data','count'));
}
My View:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET'))!!}
#foreach($clients as $client)
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email]) !!}
<article>
{{ $client->user_name }}
{{ $client->email }}
</article>
#endforeach
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
<br/>
#include('clientinfo.newmember')
#stop
if i add a button in my view naming select-all and clear-all how do i relate them, to select all the members within list?
You could give the checkboxes a class and use jquery.
You also need a checkbox that says "select all" with an ID.
$(function() {
$('#selectAll').click(function() {
if ($(this).prop('checked')) {
$('.your_checkbox_class').prop('checked', true);
} else {
$('.your_checkbox_class').prop('checked', false);
}
});
});
PS: Code is not tested
I have made changes to my code and it worked using JavaScript.
Here is my code:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET','name'=>'f1' , 'id'=>'form_id'))!!}
<br/>
#foreach($clients as $client)
<div class="form-group">
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email], ['class' => 'questionCheckBox']), $client->email !!}
<br/>
</div>
#endforeach
<div class="form-group">
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
</div>
<div class="form-group">
{!! Form::button('Select All',['class' => 'btn btn-info form-control','onClick'=>'select_all("agree", "1")']) !!}
</div>
<div class="form-group">
{!! Form::button('Clear All',['class' => 'btn btn-danger form-control','onClick'=>'select_all("agree", "0")']) !!}
</div>
{!! Form::close() !!}
#stop
#endsection
And in my master file,I have added a JavaScript:
<script type="text/javascript">
var formblock;
var forminputs;
function prepare() {
formblock= document.getElementById('form_id');
forminputs = formblock.getElementsByTagName('input');
}
function select_all(name, value) {
for (i = 0; i < forminputs.length; i++) {
// regex here to check name attribute
var regex = new RegExp(name, "i");
if (regex.test(forminputs[i].getAttribute('name'))) {
if (value == '1') {
forminputs[i].checked = true;
} else {
forminputs[i].checked = false;
}
}
}
}
if (window.addEventListener) {
window.addEventListener("load", prepare, false);
} else if (window.attachEvent) {
window.attachEvent("onload", prepare)
} else if (document.getElementById) {
window.onload = prepare;
}
</script>
Earlier i was doing this using Jquery, that was not working, then i tried using JavaScript and it worked.
I have tried various ways to add jquery in my code which are given in answers of stackoverflow.com, but nothing worked in laravel. If anyone know how to use jquery in laravel, please leave a comment.