I am not receiving any request at controller's uploadGallery method. Although, the post request is received correctly.
gallery.blade.php
<div class="row">
<form action="{{ url('file-upload') }}" method="post" class="dropzone" id="my-awesome-dropzone">
{{ csrf_field() }}
<div class="dz-message">
<h3>Drop images here or click to upload.</h3>
</div>
</form>
</div>
<script type="text/javascript">
$(function (){
Dropzone.options.myAwesomeDropzone = {
paramName: "files",
uploadMultiple:true,
maxFilesize:6,
autoProcessQueue: true,
uploadMultiple: true,
addRemoveLinks: true,
acceptedFiles: ".png, .jpg, .jpeg",
dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",
dictRemoveFile: "Remove",
dictFileTooBig:"Image is bigger than 6MB",
accept: function(file, done) {
console.log("Uploaded");
done();
},
init:function() {
/* var submitButton = document.querySelector('#submit-all')
myAwesomeDropzone = this;
submitButton.addEventListener("click", function(
myAwesomeDropzone.processQueue();
));
this.on("addedfile", function(){
$('#submit-all').show();
});*/
},
success: function(file,done){
console.log("All files done!");
}
}
});
</script>
web.php
Route::get('/gallery', 'PagesController#Gallery');
Route::post('/file-upload', 'ImagesController#uploadImages');
ImagesController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ImagesController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function uploadImages(Image $request) {
$images = request()->file('files');
dd($images);
return view('Gallery');
}
}
Anything inside the uploadImages function is not running. Why?
You have wrong type hinting in your uploadImages() function.
Change your uploadImages() from
public function uploadImages(Image $request)
to
public function uploadImages(Request $request)
Now you should be able to use request() to grab files.
Change this
public function uploadImages(Image $request) {
$images = request()->file('files');
dd($images);
return view('Gallery');
}
to and replace request() with $request since your using eloquent.
public function uploadImages(Request $request) {
$images = $request->file('files');
dd($images);
return view('Gallery');
}
For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications
Related
I have a problem in which I cannot trace the error/problem when trying to export and download my Users table in excel using Maatwebsite I've followed step by step with this reference here link but it didn't export the data through excel,
Is there any wrong with my implementation? Is somebody have an idea what's the problem? I appreciate any comments
index.blade.ph
<li class="navi-item">
<a href="#" class="navi-link">
<span class="navi-icon">
<i class="la la-file-excel-o"></i>
</span>
<span class="navi-text" #click="exportData()">Excel</span>
</a>
</li>
Index.js
methods: {
init() {
var vm = this;
var t;
$(document).ready(function() {
vm.$toaster.init();
vm.setConfig();
});
},
exportData(){
let vm = this;
$.ajax({
url: vm.$route('staff.ajax.emvvalidationdetails.exportemv'),
type: 'GET',
success: function (response) {
if (response) {
// console.log("Test");
}
},
});
},
Staff ajax
Route::group(['prefix' => 'emvvalidationdetails', 'namespace' => 'Emvvalidationdetails'], function () {
Route::get('exportemv', 'EmvvalidationdetailsController#exportemv')->name('staff.ajax.emvvalidationdetails.exportemv');
});
EmvvalidationdetailsController
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportUser;
use App\Exports\ExportUser;
use App\Models\User;
public function exportemv(Request $request){
return Excel::download(new ExportUser, 'users.xlsx');
}
ExportUser.php in app/Exports
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportUser implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select('username','email','password')->get();
}
}
you can download it this way
Download
My guess is that the response's Content-Type is not being set correctly. Maybe it gets messed up by some package or other part of your codes. See the doc here to manually set the Content-Type.
So my friend and I are working on an admin view for user management. I wanted this view to be able to delete users by clicking a button.
The user list itself looks like this:
#section('main')
#csrf
<ul class="collapsible">
#foreach($users as $user)
<li method="POST" action="delete">
<div class="collapsible-header">
<i class="material-icons">face</i>{{$user->fname}} {{$user->lname}}
</div>
<div class="collapsible-body" id="{{$user->id}}">
<p>Adresse: {{$user->address1}}, {{$user->postalcode}} {{$user->city}}</p>
<p>Land: {{$user->country}}</p>
<p>E-Mail: {{$user->email}}</p>
<span>Beigetreten: {{$user->created_at}}</span>
<br>
<a class="btn red waves-effect waves-light user-delete-button" href=""
id="user-delete-button" data-userid="{{$user->id}}">
<i class="material-icons">delete</i>
</a>
</div>
</li>
#endforeach
</ul>
#endsection
The script in the extended dashboard.blade.php template is the following:
<script>
$(document).ready(function(){
$('.collapsible').collapsible();
$('.user-delete-button').click(function (e){
$.ajax({
url: '{{route('deleteuser')}}',
data: {"userid": $(this).data("userid")},
type: 'post',
success: function(data)
{
console.log('deleted');
}
});
});
});
</script>
The UserController:
class UserController extends Controller
{
public static function destroy($id) {
$user = \App\Models\User::findOrFail($id);
$user->delete();
return redirect('/userlist');
}
//
}
And at last the Route in the web.php:
Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');
So now whenever I am trying to delete a user clicking the button, I get an "500 Internal Server Error" in the console.
At this point I am more than just clueless as to what I am supposed to do to make this work.
The only thing I want is to delete a record and refresh the database by simply clicking a button. But currently nothing I tried worked so far.
I hope you can help me. Thanks in advance!
your must need header file in your request so use this
type:'post',
header
Option 1: Add {id} parameter to your route.
Route::post('/deleteuser/{userid}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
class UserController extends Controller
{
public function destroy($userid) {
$user = User::findOrFail($userid);
$user->delete();
return redirect('/userlist');
}
}
Option 2: Use Route Model Binding in your route and controller action:
Route::post('/deleteuser/{user}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
class UserController extends Controller
{
public function destroy(User $user) {
$user->delete();
return redirect('/userlist');
}
}
Option 3: Use Request object to retrieve query string
Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function destroy(Request $request) {
$user = User::findOrFail($request->query('userid', null));
$user->delete();
return redirect('/userlist');
}
}
Maybe you were getting 500 error because your controller class was not found. You need to use full namespace. Modify your code as follows:
Route:
Route::post('/deleteuser', [App\Http\Controllers\UserController::class, 'destroy'])->name('deleteuser');
Controller:
class UserController extends Controller
{
public static function destroy(Request $Request) {
$id = $Request->input('userid');
$user = \App\Models\User::findOrFail($id);
$user->delete();
return redirect('/userlist');
}
}
N.B: For POST request, you need to send csrf token via your ajax data
data: {
"_token": "{{ csrf_token() }}",
"userid": $(this).data("userid")
}
or you can add header parmas like this way:
$.ajax({
url: '{{route('deleteuser')}}',
data: {"userid": $(this).data("userid")},
type: 'post',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
success: function(data)
{
console.log('deleted');
}
});
Hope this will work!
I have a rather old site that I have inherited as part of a new position - it's been built to Laravel 4.1.* version specs.
My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.
application.blade.php
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] returns what I input into the form. The above "response" simple chucks back html - so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
ApplicationController.php:
<?php
use Illuminate\Http\Request;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
Any pro-tips would be greatly appreciated!
to check what your are missing in controller when posting or getting your result
usually which i follow
in blade.php
<.form method="post" action="{{url('supply-us/application')}}".>
{{csrf_field()}}
<.input type="text" name="companyName".>
<./form.>
remove dot try this it will help you to find missing thing in controller
in your blade
<.input type="text" name="companyName" id="companyName".>
in your ajax
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
in your controller
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}
Why is it the file i upload not reflecting on the request even though the file is uploaded successfully?
HTML
<div id="upload_excel" class="dropzone form-control">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
JS
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::getToken() }}";
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#upload_excel", {
paramName: "file",
acceptedFiles: ".xls,.xlsx",
maxFiles: 1,
maxFilesize: 10,
url: baseUrl + "/upload",
params: {
_token: token
}
});
Controller
class UploadsController extends Controller
{
public function upload(Request $request) {
return $file = $request->all();
}
}
Request Preview
[
Request Response
{"_token":"ePssa9sPZxTcRR0Q4Q8EwWKjODXQ8YpCcH8H9wRP","upload_date":"2016-08-02","file":{}}
Did i miss something or what?
I have a controller like this
public function upload(Request $request) {
// validation etc
// ...
// I have a table and therefore model to list all excels
$excelfile = ExcelFile::fromForm($request->file('file'));
// return whater ...
}
In my ExcelFile Model
protected $baseDir = 'uploads/excels';
public static function fromForm(UploadedFile $file) {
$excelfile = new static;
$name = time() . $file->getClientOriginalName();
$name = preg_replace('/\s+/', '', $name);
$excelfile->path = $excelfile->baseDir . '/' . $name;
$file->move($excelfile->baseDir, $name);
return $excelfile;
}
You will also need to add UploadedFile in your Model
use symfony\Component\HttpFoundation\File\UploadedFile;
My dropzone is defined like this to ensure correct token handling
<form action="/users/{{ $id }}/media/excelupload" id="drop-zone" class="dz dropzone">
{{ csrf_field() }}
</form>
<script>
new Dropzone("#drop-zone", {
maxFilesize: 3, // MB
maxFiles: 10,
dictDefaultMessage: "Upload Excel.",
init: function() {
var known = false;
this.on("success", function(file, responseText) {
// do stuff
});
this.on('error', function() {
// aler stuff
});
this.on("addedfile", function() {
if (this.files[10]!=null){
this.removeFile(this.files[0]);
if (known === false) {
alert('Max. 10 Uploads!')
known = true;
}
}
});
}
});
</script>
I hope this helps
so I have an ajax call to a contoller which is logging me in, I know this is working because of Auth::check($user) and the returned cookie data, such as the laravel session cookie.
However, my problem is in my routes.php, I still can't get to the authorized only pages, and keep hitting the welcome view.
My routes.php:
use App\punsmodel;
use Illuminate\Http\Request;
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken'
]);
if (Auth::guest()) {
Route::get('/', function () {
return view('welcome');
});
} else {
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return view('mainview');
});
Route::get('mainview', function () {
return view('mainviewMolly');
});
});
}
My controller:
namespace App\Http\Controllers;
use App\Email;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Google_Client;
use Auth;
use App\User;
class verify extends Controller
{
public function verifyIdToken(Request $request)
{
$user = User::where('name', 'Molly')->first();
Auth::login($user);
if (Auth::check($user))
{
return response()->json(['Logged In' => "Yes!"]);
}
}
}
So I do an ajax request to the above controller, which works as I get the json response that says I was logged in, however then when I refresh the homepage, I still get the welcome page not the mainview. Why is this the case?
My ajax request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "http://mysite.come/google",
data: { email: profile.getEmail(),
id: id_token }
}).done(function() {
$("#google").text("You Are Indeed Who I Thought You Were! :)");
}).fail(function() {
$("#google").text("You Are Not Who I Thought You Were, Please Go Away!");
setTimeout(function() {
window.location = "https://en.wikipedia.org/wiki/Special:Random";
//}, 4000);
}, 9999999000);
})