How do I attach the excel file to the email? - php

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;
}

Related

Cant Download Excel file When calling Laravel Controller from AngularJS

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');

Laravel: access to variables inside facades

The code below is the method for sending the feedback message by Laravel. I want to create the variables which values are html fields names. However, the $email_fieldName is not accessibleinside the Mail::send .../
public function sendFeedback(Request $request) {
$email_fieldName = 'email';
// ...
if ($request ->isMethod('post')) {
// ...
$inputedData = $request->all();
// $email_fieldName is accessible here
$result = Mail::send('email', ['inputedData' => $inputedData], function($message) use ($inputedData) {
// $email_fieldName is not accessible here
$message->from($inputedData[$email_fieldName], $inputedData[$name_fieldName]);
// ...
});
}
}
I tried below simulation fiddle and it works. What wrong with the variable access in the code above?
$nameKey = "name";
$testBool = true;
if ($testBool) {
$array= array("name"=>"Alex", "age"=>22, "student" => true);
echo($array[$nameKey]);
}
The Mail function can't find the $email_fieldName as you haven't mention it inside use()
Change
$result = Mail::send('email', ['inputedData' => $inputedData], function($message) use ($inputedData) {
with.
$result = Mail::send('email', ['inputedData' => $inputedData], function($message) use ($inputedData, $email_fieldName) {
That's because you are in the anonymous callback of the Mail::send method. $email_fielName is not in that scope.
The same way you have use ($inputedData), you should should add $email_fieldName :
Mail::send('email', ['inputedData' => $inputedData], function($message) use ($inputedData, $email_fieldName) {
(And probably $name_fieldName too given your code)

Attach generate pdf into mail in Laravel

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

The requested URL was not found on this server but works local

I have a Laravel setup where I can add files and remove them. Now when I try to remove icons on my site on the server I get
Not Found
The requested URL /icons/24 was not found on this server.
Uploading the files and retrieving the files works. When I test it locally it works. And I do it the exact same way as with images, video files and audio files, and those all work on the server.
To debug it I also added the show() function in the controller, and that one also gives the same problem. What is going on?
routes/web.php: (partially)
Route::get('iconFile/{id}','IconController#iconFile');
Route::get('imageFile/{id}','ImageController#imageFile');
Route::get('audioFile/{id}','AudioController#audioFile');
Route::get('videoFile/{id}','VideoController#videoFile');
Route::get('signlanguageFile/{id}','SignlanguageController#signlanguageFile');
Route::group(['middleware' => ['auth']], function() {
Route::post('image-upload-with-validation',['as'=>'postimage','uses'=>'ImageController#postImage']);
Route::post('icon-upload-with-validation',['as'=>'posticon','uses'=>'IconController#postIcon']);
Route::resource('texts', 'TextController');
Route::resource('icons', 'IconController');
Route::resource('images', 'ImageController');
Route::resource('videos', 'VideoController');
Route::resource('signlanguages', 'SignlanguageController');
Route::resource('audios', 'AudioController');
});
IconController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Icon;
use Storage;
class IconController extends Controller
{
public function iconFile($id)
{
$icon = Icon::find($id);
$contents = Storage::disk('local')->get('uploads/icons/'.$icon->file);
$response = Response($contents);
$response->header('Content-Type', 'icon');
return $response;
}
public function show($id)
{
$icon = Icon::find($id);
$data = [
'icon' => $icon
];
echo $icon;
//return view('icon', $data);
}
public function postIcon(Request $request)
{
$this->validate($request, [
'icon_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
]);
$iconName = time().'.'.$request->icon_file->getClientOriginalExtension();
$request->icon_file->move(storage_path('app/uploads/icons'), $iconName);
$icon = new Icon;
$icon->parent_id = $request->parent_id;
$icon->file = $iconName;
$icon->save();
return back()
->with('success','You have successfully uploaded an icon.')
->with('icon',$iconName);
}
public function destroy($id)
{
$icon = Icon::find($id);
$section_id = $icon->parent_id;
Storage::delete('uploads/icons/'.$icon->file);
$icon->delete();
return redirect('/section/'.$section_id)->with('success','Icon deleted.');
}
}
Update:
i tried replacing the resource route to Route::resource('iconz', 'IconController'); (with a z) and then it works! Changing it back to "icons" makes it stop working again. Could icons be some kind of reserved word?
Also tried php artisan route:clear which didn't help.

Export data to Excel in Laravel

I want to make export data into excel in my project, i have made it, but after I check the results, the results doesnt like what I want. here I would like to make a result there is a title table.
This code my controller:
public function getExport(){
Excel::create('Export data', function($excel) {
$excel->sheet('Sheet 1', function($sheet) {
$products=DB::table('log_patrols')
->join("cms_companies","cms_companies.id","=","log_patrols.id_cms_companies")
->join("securities","securities.id","=","log_patrols.id_securities")
->select("log_patrols.*","cms_companies.name as nama_companies","securities.name as nama_security")
->get();
foreach($products as $product) {
$data[] = array(
$product->date_start,
$product->date_end,
$product->condition_status,
$product->nama_security,
$product->nama_companies,
);
}
$sheet->fromArray($data);
});
})->export('xls');
}
this my problem result :
and it should be :
my problem is how to change the number into text what i want in the header table.
what improvements do i have to make to the code to achieve my goal?
NB : i use maatwebsite/excel
From the official docs:
By default the export will use the keys of your array (or model
attribute names) as first row (header column). To change this
behaviour you can edit the default config setting
(excel::export.generate_heading_by_indices) or pass false as 5th
parameter:
Change:
$sheet->fromArray($data); to $sheet->fromArray($data, null, 'A1', false, false);
how to change the number into text what i want in the header table.
Then you can define your own heading and prepend it to the first row of the sheet.
$headings = array('date start', 'date end', 'status condition', 'security', 'company');
$sheet->prependRow(1, $headings);
That should make it work.
Try this in your controller
$data=Insertion::get()->toArray();
return Excel::create('yourfilename', function($excel) use ($data) {
$excel->sheet('mySheet', function($sheet) use ($data)
{
$sheet->cell('A1:C1',function($cell)
{
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});
$sheet->cell('A:C',function($cell)
{
$cell->setAlignment('center');
});
$sheet->cell('A1', function($cell)
{
$cell->setValue('S.No');
});
$sheet->cell('B1', function($cell)
{
$cell->setValue('Name');
});
$sheet->cell('C1', function($cell)
{
$cell->setValue('Father Name');
});
if (!empty($data)) {
$sno=1;
foreach ($data as $key => $value)
{
$i= $key+2;
$sheet->cell('A'.$i, $sno);
$sheet->cell('B'.$i, $value['name']);
$sheet->cell('C'.$i, $value['fathername']);
$sno++;
}
}
});
})->download(xlsx);

Categories