dropzone server implementation - laravel

I just started using the dropzone plugin and i'm using laravel in my project. I want to know how to get the files uploaded so i can store them in my database. this is my view :
<form action="{{route('realisation.storeimg')}}" method="POST" files="true" enctype="multipart/form-data"
data-toggle="validator" role="form" class="dropzone" id="my-awesome-dropzone">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="table table-striped" class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail/></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
<input type="hidden" name="realisation_id" value="{{$realisation->id}}">
</form>
my route for the upload:
Route::post('/storeimg',[
'as'=>'realisation.storeimg',
'uses'=>'RealisationController#storeimg'
]);
my controller:
public function storeimg (Request $request)
{
$realisation = Realisation::where('id','realisation_id')->first();
if($request->file('image')) {
foreach ($request->file('image') as $image) {
$realisation_image = Realisationimg::where('realisation_id','realisation_id')->first();
File::delete($realisation_image->image);
File::delete($realisation_image->image_thumb);
$extension = $image->getClientOriginalExtension();
$name = substr($image->getClientOriginalName(), 0, -4);
list($width, $height) = getimagesize($image);
$imgname = str_slug($name, '_');
$filename = $imgname.'.'.$extension;
if(file_exists('uploads/realisationimg/cover/' . $filename)){
do {
$newname = $imgname.'_'.str_random(3) . '.' . $extension;
}
while(file_exists('uploads/realisationimg/cover/' . $newname));
$filename = $newname;
}
$path = 'uploads/realisationimg/cover/'.$filename;
$path_thumb = 'uploads/realisationimg/thumb/'.$filename;
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path);
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path_thumb);
$realisation_image->image = $path;
$realisation_image->image_thumb = $path_thumb;
$realisation_image->realisation_id = $id;
$realisation_image->save();
}
}
Session::flash('ajouter','ok');
return redirect(route('realisation.edit',['id'=>$request->get('realisation_id')]));
}
in the dropzone.js file i changed the default options to the following:
uploadMultiple: true,
paramName: "image",
when i submit the dropzone form nothing gets executed (no files are stored and nothing in my database). can someone point to me my mistake? thanks.

Here is s sample code that might help.
Route:
Route::post('/storeimg', 'GalleryController#storeimg')
->name('realisation.storeimg');
Controller:
public function storeimg(Request $request)
{
$path = $request->file('file')->store('public/photo');
if (!$path)
return url('storage');
$dirs = explode('/', $path);
if ($dirs[0] === 'public')
$dirs[0] = 'storage';
$data['image'] = url(implode('/', $dirs));
Photo::create($data);
session()->flash('success', 'Photos uploaded successfully');
return response()->json(['success'=>$data['image']]);
}
View: Just open file to send files to controller.
{!! Form::open([ 'route' => [ 'realisation.storeimg'], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{!! Form::close() !!}
<link rel="stylesheet" href="../dropzone.min.css">
<script src="../dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize : 1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
//Remove Photo
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
console.log(id);
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
});
});
</script>
This is result in a dropzone box where you can add multiple photos at a time

Related

why my submit form not working on mobile phone?

I use laravel 9 and i have a registration form and submit button for some reason doesn't work in mobile phone only, but its working fine in desktop. Any idea what wrong? Thankyou!
Html (blade):
<form action="{{ route('jokibukti') }}" method="POST">
#csrf
<td width="25%">{{ $item->keterangan }} <input type="text"
id="ketbaru" name="keteranganbaru" class="form-control"
placeholder="Masukan Bonus Disini!"></td>
{{-- <td width="7%"><a class="btn btn-primary btn-sm" onclick=''>Selesai</a> --}}
<td width="25%">
<input type="hidden" name="id" value="{{ $item->id }}">
<label class="">
<span class="sr-only">Pilih Gambar</span>
<input type="file" name="image" class="" />
#error('image')
<span class="text-red-600 text-sm">{{ $message }}</span>
#enderror
</label>
<button type="submit" value="submit" class="btn btn-primary btn-sm">Submit</button>
</form>
Route :
Route::post('/joki/bukti', [ControllerJoki::class, 'buktiselesai'])->name('jokibukti');
Controller :
public function buktiselesai(Request $request)
{
// #dd($request->image);
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
$ketbaru = $request->keteranganbaru;
$ketlamauser = Jokiongoing::where('id', $request->id)->first();
$ketlama = $ketlamauser->keterangan;
if ($ketlama != "") {
$keterangan = $ketlama . " & " . $ketbaru;
} else {
$keterangan = $ketbaru;
}
// $image_path = $request->file('image')->store('buktijoki', 'public');
$imageName = time() . '.' . $request->image->extension();
$request->image->move(public_path('buktijoki'), $imageName);
$data = Jokiongoing::where('id', $request->id)->update([
'bukti' => $imageName,
'keterangan' => $keterangan,
'acc' => '1',
]);
if ($data) {
return redirect()->route('jokiaktif')->with(['success' => 'Bukti Berhasil disimpan']);
} else {
return redirect()->route('jokiaktif')->with(['error' => 'Bukti Gagal Disimpan']);
}
}
<script>
var tap = true;
document.addEventListener('touchstart', function(e) {
tap = true;
});
document.addEventListener('touchmove', function(e) {
tap = false;
});
document.addEventListener('touchend', function(e) {
if (tap) {
//users tapped the screen
}
});
</script>
Trying adding this script from someone in the stackoverflow, but get nothing as result.
Im try to add onClick to the button
<button onClick = "testsubmit()" value="submit" class="btn btn-primary btn-sm">Submit</button>
<script>
function testsubmit() {
alert("masuk");
}
</script>
and its work fine, what happen to type="submit" ?

Ajax datatable is not inserting

I am studying about ajax datatabl. My AJAX datatable insert is not working. It has no error on console or whatsoever. It's just whenever I am inserting, the datatable is just refreshing. Is there anything that I missed? I have provided my codes below. Any help will be appreciated. Thank you very much.
This is the result whenever i'm adding. But it's not adding on database or whatsoever.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%">Name</th>
<th width="35%">Email</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<!-- <input type="file" name="user_image" id="user_image" /> -->
<!-- <span id="user_uploaded_image"></span> -->
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 3],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
if(name != '' && email != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
console.log(name);
console.log(email);
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
});
</script>
Controller:
function fetch_user(){
$this->load->model("profiles");
$fetch_data = $this->profiles->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = $row->name;
$sub_array[] = $row->email;
$sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"] )),
"recordsTotal" => $this->profiles->get_all_data(),
"recordsFiltered" => $this->profiles->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post("email.")
);
$this->load->model('profiles');
$this->profiles->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profiles");
$data = $this->profiles->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['name'] = $row->name;
$output['email'] = $row->email;
}
echo json_encode($output);
}
}
Model:
var $table = "userss";
var $select_column = array("id", "name", "email");
var $order_column = array(null, "name", "email", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("name", $_POST["search"]["value"]);
$this->db->or_like("email", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('id', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if($_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud()
{
$this->db->insert('userss', $data);
}
What is your database structure? Is the table called userss or users?
$this->db->insert('userss', $data); <--Possible typo?
You likely will need to use the inspect feature of your browser and look at any responses under the network tab to see any errors.

Ajax script to update record does not work, Laravel

I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>

Laravel get a empty variable from axios.post from vuie.js module

partners from stackOverflow im making a module using laravel like backend, and vue.js by frontend, i have a form to create a new entity, but the controller dont get the values¡, plz help me to find the error. I'm going to share the code.
the routes.web
//new event from API
Route::resource('/api/events', 'EventsController', ['except' => 'show','create']);
The function in the controller EventsController.php
<?php
namespace soColfecar\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use soColfecar\Http\Requests\CreateEventRequest;
use soColfecar\Http\Requests\UpdateEventRequest;
use soColfecar\User;
use soColfecar\Change;
use soColfecar\Event;
use soColfecar\Event_type;
use Auth;
public function store(Request $request)
{
$exploded = explode(',', $request->banner);
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0],'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/storage/banner/'.$fileName;
file_put_contents($path, $decoded);
Event::create([
'event' => strtoupper($request['event']),
'id_event_type' => $request['id_event_type'],
'date_init' => $request['date_init'],
'date_end' => $request['date_end'],
//'banner' => $fileName,
]);
Change::create([
'description' => 'Creo el de evento:'.$request['event'].' correctamente.',
'id_item' => 10,
'id_user' => Auth::user()->id,
]);
return redirect()->route('events.index')
->with('info', 'evento guardado con exito');
}
the method:
<form method="POST" v-on:submit.prevent="storeNewEvent">
<div class="form-group m-form__group">
<label for="eventTypeInput">Tipo de vento:</label>
<v-select :options="eventTypes" v-model="newEvent.id_event_type" id="eventTypeInput">
<template slot="option" slot-scope="option">
{{ option.label }}
</template>
</v-select>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.city_id }}</span>
</div>
<div class="form-group m-form__group">
<label for="inputHotelName">Nombre del Evento</label>
<input type="text" class="form-control" name="inputHotelName" v-model="newEvent.event" placeholder="Nombre del Evento">
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.hotel_name }}</span>
</div>
<div class="form-group m-form__group">
<label for="date_init_imput">Fecha de inicio</label>
<input class="form-control" type="date" v-model="newEvent.date_init" value="" id="date_init_imput">
</div>
<div class="form-group m-form__group">
<label for="date_end_imput">Fecha de finalizacion</label>
<input class="form-control" type="date" v-model="newEvent.date_end" value="" id="date_end_imput">
</div>
<div class="form-group m-form__group">
<label for="customFile">Banner del Evento</label>
<div></div>
<div class="custom-file">
<input type="file" class="custom-file-input" #change="getLogo" id="customFile">
<label class="custom-file-label" for="customFile">Seleccione archivo</label>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.logo }}</span>
</div>
</div>
<hr>
<button type="submit" class="btn btn-info waves-effect text-left">Guardar</button>
</form>
data() {
return {
changes: [],
eventTypes: [],
errors: [],
newEvent: {
event: '',
id_event_type: '',
date_init: '',
date_end: '',
banner: '',
}
}
},
storeNewEvent : function() {
var url = 'api/events';
var newEvent = this.newEvent
axios.post(url, {event: this.newEvent}).then(response => {
this.newEvent = {}
this.errors = [];
$('#new_event_modal').modal('hide');
$('.modal-backdrop').remove();
toastr.success('Se ha creado el evento con exito!')
}).catch(error => {
this.errors = error.response.data
});
},
And the error
"Too few arguments to function soColfecar\Http\Controllers\EventsController::store(), 0 passed and exactly 1 expected"
enter image description here
You need to type hint the $request so Laravel knows to fill it in ("dependency injection").
At the top of your file:
use Illuminate\Http\Request;
Then, for your function:
public function store(Request $request) {

Ajax post request- Unresolvable dependency resolving and error 500

I'm trying to create a multi-step form using jQuery anad AJAX. But Im getting this error when "go to step 2" is clicked:
jquery.min.js:4 POST http://store.test/product/1/product-test/payment/storeUserInfo 500 (Internal Server Error)
Also when clicking in network tab and then click in "storeUserInfo" it appears:
exception
:
"Illuminate\Contracts\Container\BindingResolutionException"
file
:
"/Users/jakeB/projects/store/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line
:
933
message
:
"Unresolvable dependency resolving [Parameter #1 [ <required> array $data ]] in class Illuminate\Validation\Validator"
Do you know where is the error?
In the PaymentController there is the storeUserInfo() Method that is the method for the step 1:
public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
Route:
Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
'uses' => 'PaymentController#storeUserInfo',
'as' =>'products.storeUserInfo'
]);
// step 1 and step 2 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" id="step1form" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input name="name" type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// ajax in payment.blade.php
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
console.log(data);
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
$('#response').show().html(errorsHtml);
}
});
});
});
Use Validator facade class in your PaymentController
use Validator;
class PaymentController extends Controller
{
public function storeUserInfo(Request $request, $id, $slug = null){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
}

Resources