Hi I am sending some data to laravel controller from angularjs and based on that data i want get data from sql table and download as excel file.But i am unable to download the file
Angular code
$scope.sendSetField = function (selected_list) {
var arr = [];
angular.forEach(selected_list, function(value, key){
arr.push(key);
});
//console.log(selected_list);
$http.post("http://localhost/maxo_ats_v1.00/dashboard/jobsDownload",arr)
.then(function(response) {
});
Laravel Controller :
public function downloadJobsList(Request $request)
{
// $jobs = CnfFormField::select('id', 'name', 'email', 'created_at')->get();
$jobs = Input::all();
// return view('jobs.columnSelect',compact['data']);
$data = Jobs::select($jobs)->get();
Excel::create('Job', function($excel) use ($data) {
$excel->sheet('mySheet', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download('xlsx');
}
Route
Route::post('dashboard/jobsDownload','JobsController#downloadJobsList');
Related
Application unable to handle the request for more than 10k records
public function downloadProductData() {
header('Content-Type: text/csv');
\Maatwebsite\Excel\Facades\Excel::create('BulkAddGamesUploadTemplate', function($excel) {
$excel->sheet('UploadGames', function($sheet) {
$sheet->fromArray(
array("id","product_code","product_des","product_tag","product_meta","product_title")
);
$product_data = DB::table('products')->select("id","product_code","product_des","product_tag","product_meta","product_title")
$this->temp_counter = 2;
$product_data->each(function ($game_config) use ($sheet) {
for($i=1;$i<3;$i++){
$sheet->setCellValue('A'.$this->temp_counter,$product_data->product_code);
$sheet->setCellValue('B'.$this->temp_counter,$product_data->product_des);
$sheet->setCellValue('C'.$this->temp_counter,$product_data->product_des);
$sheet->setCellValue('D'.$this->temp_counter,$product_data->product_tag);
$this->temp_counter++;
}
})
});
})->download('xls');
}
I've some problem with email attach generate pdf, hope you can give me some advice, please kindly help.
Here is the Controller:
public function kirim(Request $request){
$keluhan = keluhan::findOrFail($request->id);
$tindak = DB::table('tindakans')
->join('keluhans','keluhans.id','=','tindakans.id_keluhan')
->select(DB::raw('tindakans.id, id_keluhan, perbaikan_sementara, revisi_dokumen, target_verifikasi, ttd_tanggung1,
ttd_tanggung2'))->get();
$analisa = DB::table('analisas')
->join('tindakans','tindakans.id','=','analisas.id_tindakan')
->join('keluhans','keluhans.id','=','tindakans.id_keluhan')
->select(DB::raw('id_tindakan, analisa, tindakan, pic, tanggal_pelaksanaan'))->get();
$pdf = \PDF::loadView('laporan.ptkp',compact('keluhan','tindak','analisa','halaman'));
//return $pdf->stream();
$data = array(
'email_address'=>$request->email_address,
'cc'=>$request->cc,
'subject'=>$request->subject,
'keterangantambahan'=>$request->keterangantambahan
);
Mail::send('laporan.kirim', $data, function($message) use($data) {
$message->from('christian7andrew#gmail.com', 'PuraBox');
$message->to($data['email_address']);
if($data['cc'] != null){
$message->cc($data['cc']);
}
$message->subject($data['subject']);
$message->Attach($pdf);
});
return redirect('/');
}
How can I attach $pdf?
For future Googlers:
Since Laravel 5.1 you can use attachData() method to directly attach generated file without the need for saving it.
Source:
Manual - section Raw Data Attachments
The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders.shipped')
->attachData($this->pdf, 'name.pdf', [
'mime' => 'application/pdf',
]);
}
You are using:
$message->Attach($pdf);
To add attachments to an e-mail, use the attach method on the $message object passed to your Closure. The attach method accepts the full path to the file as its first argument:
Source
You should use the attach method (without the capitalize letter), and in the parameter, you need to pass the path where the pdf is, not the generated pdf. like the docs says.
$message->attach($pathToFile);
In the end, will be something like that:
Mail::send('laporan.kirim', $data, function($message) use($data) {
$message->from('christian7andrew#gmail.com', 'PuraBox');
$message->to($data['email_address']);
if($data['cc'] != null){
$message->cc($data['cc']);
}
$message->subject($data['subject']);
//Full path with the pdf name
$message->attach('foo/bar/mypdfname.pdf');
});
I don't know which library you are using for PDF generation, but I guess there should be an API something like this,
$pdf = \PDF::loadView('laporan.ptkp',compact('keluhan','tindak','analisa','halaman'));
$path = storage_path('app/public/pdf/')."example.pdf";
$pdf->save($path);
return $path;
And then you can use the path to attach to email.
Hope this helps.
it's very simple just add your blade in the loadView() method and pass it's pdf instance into callback
public function index()
{
$data["email"] = "contact#cdlcell.com";
$data["title"] = "cdlcell";
$data["body"] = "Demo";
$pdf = PDF::loadView('emails.myTestMail', $data);
Mail::send('emails.myTestMail', $data, function($message)use($data, $pdf) {
$message->to($data["email"], $data["email"])
->subject($data["title"])
->attachData($pdf->output(), "text.pdf");
});
dd('Mail sent successfully');
}
May be you can do something as
Mail::send('laporan.kirim', $data, function($message) use($data) {
$message->from('christian7andrew#gmail.com', 'PuraBox');
$message->to($data['email_address']);
if($data['cc'] != null){
$message->cc($data['cc']);
}
$message->subject($data['subject']);
$message->Attach($pdf->output(),"name.pdf");
});
return redirect('/');
}
this may help you out
I think Im close, I just need to pass the $excelFile in Mail but it keeps saying its undefined, yet when I pass $truckstop_post it goes through but that data is not formatted correctly bc it didnt go through the Excel::create yet. How do I get the result of \Excel::create into the Mail::send??
public function truckstopPost()
{
$type = 'csv';
$truckstop_post = Loadlist::select('pick_city', 'pick_state', 'delivery_city', 'delivery_state', 'trailer_type', 'pick_date', 'load_type', 'length', 'width', 'height', 'weight', 'offer_money', 'special_instructions', 'company_contact', 'contact_phone')->where('urgency', 'OPEN')->orderBy('id', 'desc')->get();
$excelFile = \Excel::create('itransys', function($excel) use ($truckstop_post) {
$excel->sheet('mySheet', function($sheet) use ($truckstop_post)
{
$sheet->fromArray($truckstop_post);
});
$info = Load::find(8500);
$info = ['info'=>$info];
Mail::send(['html'=>'email.invoice_email_body'], $info, function($message) use ($info, $excelFile){
$message->to('mike#gmail.com')->subject('subject');
$message->from('mike#gmail.com', \Auth::user()->name);
$message->attachData($excelFile, 'Invoice.csv');
});
});
return back()->with('status', 'You Posted Truckstop!');
}
This is what the results look like if I pass $truckstop_post into attachData() but of course thats not a nicely formatted csv file
You can do it like so
use Maatwebsite\Excel\Excel as BaseExcel;
use Maatwebsite\Excel\Facades\Excel;
...
$filename = "my_file.csv";
$attachment = Excel::raw(
new PurchaseOrderLinesExport($this->data),
BaseExcel::CSV
);
$subject = "Purchase Order"
return $this->from($this->employee->email)
->subject("Purchase Order)
->view('emails.view')
->attachData($attachment, $filename);
Excel::raw() method creates/writes a temporary file and then gets its contents and delete after deleting that file.
Second Solution would be like this if you're using laravel:
public function build()
{
return $this->markdown('emails.report')
->attach(
Excel::download(
new AuditReport($this->audit),
'report.xlsx'
)->getFile(), ['as' => 'report.xlsx']
);
}
Excel::download() returns a BinaryFileResponse that's why it doesn't work directly, but you can grab the file.
public function post()
{
$type = 'csv';
$create_excel = List::select('pick_city', 'pick_state', 'delivery_city', 'delivery_state')->where('urgency', 'OPEN')->orderBy('id', 'desc')->get()->toArray();
$excelFile = \Excel::create('itrans', function($excel) use ($create_excel) {
$excel->sheet('mySheet', function($sheet) use ($create_excel)
{
$sheet->fromArray($create_excel);
});
})->download($type);
Mail::send(['html'=>'email.email_body'] function($message) {
$message->to('example#gmail.com')
->subject('Email Subject Line');
$message->from('daniel#twbb.com', 'Daniel');
$message->attachData($excelFile, 'Invoice.csv');
});
return $excelFile;
}
It's just since I started to discover slim and I ran into a problem, I do not know how to look for a solution because it is very strange.
Basically if I declare a function that is called from the route after another function is also called by a route, the first is not performed.
API group
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
//get information about the themer selected
$app->get('/:id','getThemer'); //AFTER THIS ROUTES /ciao AND /themes NOT WORK
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
});
});
external file with function
//external file with function
function getThemer($key,$id) {
$themer = R::find("themers","id = ?",[$id]);
echo json_encode(R::exportAll($themer));
return true;
}
function countThemer(){
echo "count";
$count = R::exec( 'SELECT COUNT(id) FROM themers' );
echo $count;
}
function allowed($key){
$app = \Slim\Slim::getInstance();
$params = $app->router()->getCurrentRoute()->getParams();
if(!($params["key"]=="giulio"))
$app->redirect ("http://google.com");
}
after the route index.php/api/giulio/themer/1 that call getThemer and work the route index.php/api/giulio/themer/ciao and index.php/api/giulio/themer/themes not work
I thank you in advance for possible help
criticism or comments on the code in 'general appearance are welcome
Change the order of the routes:
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
//get information about the themer selected
$app->get('/:id','getThemer');
});
});
Following is route:
$router->get('/securityquestionlist', [ 'as'=> 'SecurityQuestionListIndexRoute', 'uses'=> 'SecurityQuestionListController#index']);
I have following action in controller class:
public function index()
{
$model = new SecurityQuestionListModel();
$data = $model->select('question','created_at', 'updated_at', 'status')->where('status', 1)
->orderBy('created_at', 'desc')
->paginate(3);
if(Request::ajax()){
return response()->json(['rData' => $data]);
}else{
return view('securityquestionlist.index' /* ,['rData'=> $data]*/ );
}
Following is Ajax code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#IdSQLTable').DataTable({
'ajax' : 'http://localhost:9901/securityquestionlist',
'cache' : false
});
} );
</script>
I am receiving following AJAX response from server:
{"rData":{}}
Can some one guide me, in case of AJAX why $data value is not returning from server. If I disable ajax, and load normal page then value is received on client side and table rows are populated with data. Right now I have made it remarks in :
return view('securityquestionlist.index' /* ,['rData'=> $data]*/ );
Think you have to convert the data to array using toArray()
$rData = $data->toArray();
The send response using
return response()->json(['rData' => $rData]);