Maatwebsite not exporting in Laravel php - php

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.

Related

500 Internal Server Error when trying to delete mysql data record using ajax in laravel 8

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!

Ajax in Laravel not working

I am trying to achieve simple Ajax call in my web application, unfortunately it is not working.
Html code
<li id="decorative_items">
Decorative Items
</li>
Ajax code:
$(document).ready(function() {
var id = 2; /* This has nothing to do with the code */
$("#decorative_items").bind("click", function() {
alert("click event fired"); /*This is working*/
$.ajax({
type:'POST',
url:'/getDecorativeItems',
data: {'id' : id},
success:function(response) {
alert("foo");
}
});
});
});
routes/web.php
Route::post('/getDecorativeItems', 'ajaxController#fetchDecorativeItems');
ajaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
class ajaxController extends Controller
{
function fetchDecorativeItems(Request $request) {
$msg = "Reached Controller";
return response()->json(array('msg'=> $msg), 200);
}
}
I have read all the answers to related questions and other online posts but I am unable to find the error.
Note: The code is working fine, there is no syntax error but I am unable to achieve the intended output. The intended output I am looking for is alerting "foo" using Ajax
Thanks in advance
Turn on your chrome devtool, check on network -> XHR in list of your XHR request, click on your ajax request (Case your ajax request fase, it has red color ) -> preview to see what really happen, if somethings wrong on your Laravel backend code, it also show here.
See the image bellow:
Hope this helfull, don't debug by print an alert()
I got the solution.
I was missing CSRF in my Ajax function call
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

Dropzone.js post request in laravel 5.4

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

data not entered to database using Lumen (Laravel)

I am new to Laravel and Lumen framework.
I am trying to create an API using Lumen framework.I wanted to enter the data to database. But the database is updated with id, date_created and date_updated. But the data I entered are not inserted there. Instead it shows blank for string inputs and 0 for integer inputs.
Here is my controller code:
<?php
namespace App\Http\Controllers;
use App\Place;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PlaceController extends Controller{
public function savePlace(Request $request){
$place = Place::create($request->all());
return response()->json($place);
}
}
And here is my migration code:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlacesTable extends Migration
{
public function up()
{
Schema::create('places', function (Blueprint $table) {
$table->increments('id');
$table->string('place');
$table->integer('pincode');
$table->integer('bed');
$table->integer('square_feet');
$table->integer('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('places');
}
}
Am I doing it correct? Should I use any other codes along with this?
Please help.
Thanks in advance.
EDIT :
And here is my place model code :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Place extends Model{
protected $fillable = ['place', 'pincode', 'bed', 'square_feet', 'price'];
}
EDIT 2 :
I am sending the request from an angularjs app(ionic framework).
Here is my http.post code :
app.controller('NavCtrl', ['$scope', '$http', '$location', '$window', function($scope,$http,$location,$window){
$scope.data = {};
$scope.savedata = function(){
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: $headers,
data : {'place':$scope.data.place,'pincode':$scope.data.pincode,'bed':$scope.data.bed,'square_feet':$scope.data.square_feet,'price':$scope.data.price}
})
.success(function(data,status,headers,config){
console.log(data);
$scope.navigat('/success.html');
})
.error(function(){
alert("failed");
})
};
$scope.navigat = function(url){
$window.location.href=url;
};
}]);
And here is my routes.php code :
<?php
header("Access-Control-Allow-Origin: *");
$app->get('/', function () use ($app) {
return $app->version();
});
$app->post('lumen/public/add','PlaceController#savePlace');
According to this answer, the issue seems to be the way that angular is POSTing the data. Basically, it is attempting to POST data as JSON, but PHP does not do anything to turn JSON data into request query data.
To get this to work, you need to do two things.
First, you need to change the Content-Type header to application/x-www-form-urlencoded. Just changing the content type header won't resolve the issue, though, because angular is still POSTing the data as a JSON request.
Therefore, second, you need to change the data posted from the JSON format to the query string format (name=value&name=value).
So, update your code to something like this:
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: { "Content-Type" : "application/x-www-form-urlencoded" },
data : [
'place=' + encodeURIComponent($scope.data.place),
'pincode=' + encodeURIComponent($scope.data.pincode),
'bed=' + encodeURIComponent($scope.data.bed),
'square_feet=' + encodeURIComponent($scope.data.square_feet),
'price=' + encodeURIComponent($scope.data.price)
].join('&')
})

ReflectionException Class App\Http\Controllers\AdminBookingsController does not exist Laravel-5

I'm trying to load a calendar on my page using AJAX/Laravel-5. The URL the AJAX is posting to exists in my routes.php file. However for some reason I keep getting the following error:
Class App\Http\Controllers\AdminBookingsController does not exist
My jQuery call:
(function($){
$.fn.initCalendar = function(token,month,location) {
$('#calendar-overlay-wrap').html('');
$.ajax({
url: '/admin/reports/bookings/butchers',
type: 'post',
data: {
_token: token,
month: month,
location_id: location
},
dataType: 'json',
success: function(json) {
if(json['error']) {
$('#calendar-overlay-wrap').html(json['msg']);
}
$('#calendar').html(json['calendar']);
}
});
}
})(jQuery);
$(document).ready(function() {
$.fn.initCalendar(
$('input[name=_token]').val(),
$('#month').val(),
$('#location_id').val()
);
});
My routes.php file:
Route::post('admin/reports/bookings/butchers', 'AdminBookingsController#genButchersReport');
My controller file:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Booking;
use App\Location;
use App\ClassType;
use App\Classes;
use App\Http\Requests\BookingSearchRequest;
use App\Http\Requests\UpdateBookingRequest;
use App\Http\Requests\BookingReportAccountsRequest;
use Response;
use Excel;
use DB;
class AdminBookingsController extends Controller
{
/**
* Generate booking report for butchers.
*
* #return Response
*/
public function genButchersReport()
{
echo "Hi!...";exit;
}
}
I have tried running composer dump-autoload but this does not seem to have any effect on the error.
Please help.
I managed to resolve this as my controller was inside a sub folder. I changed my route and now it works.
Route::post('admin/reports/bookings/butchers', 'Admin\AdminBookingsController#genButchersReport');
This error popped up for me when I accidentally typed return = $variablename instead of return $variablename in one of my controller files. Maybe it will help somebody.

Categories