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
Related
I am trying to generate a PDF with some details of an individual user using the Barryvdh DomPDF library but having some problems trying to generate it.
Controller method:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = (new \Barryvdh\DomPDF\PDF)->loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Here is how I am referencing the route.
Download PDF
Route:
$router->get(
'/downloadPDF/{card}',
[
'as' => 'get::admin.download-pdf',
'uses' => 'EditCardController#downloadPDF',
]
);
I get this error:
Type error: Too few arguments to function
Barryvdh\DomPDF\PDF::__construct(), 0 passed in EditCardController.php
and exactly 4 expected.
I'm confused by this as I've seen many samples of using pdf and laravel where you don't need to pass four arguments so was wondering why this would be?
According to documentation, you should use facade instead of constructor:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = PDF::loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Kindly use below format
$data = [
'title' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
];
$pdf = App::make('dompdf.wrapper');
$pdf->loadView('bill',$data);
return $pdf->stream();
How can I remove the parameters from a URL after processing in my controller? Like this one:
mydomain/mypage?filter%5Bstatus_id%5D
to
mydomain/mypage
I want to remove the parameters after the ? then I want to use the new URL in my view file. Is this possible in laravel 5.2? I have been trying to use other approaches but unfortunately they are not working well as expected. I also want to include my data in my view file. The existing functionality is like this:
public function processData(IndexRequest $request){
//process data and other checkings
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I want it to be like:
public function processData(IndexRequest $request){
//process data and other checkings
// when checking the full url is
// mydomain/mypage?filter%5Bstatus_id%5D
// then I want to remove the parameters after the question mark which can be done by doing
// request()->url()
// And now I want to change the currently used url using the request()->url() data
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I'm stuck here for days already. Any inputs are appreciated.
You can use request()->url(), it will return the URL without the parameters
public function processData(IndexRequest $request){
$url_with_parameters = $request()->url();
$url= explode("?", $url_with_parameters );
//avoid redirect loop
if (isset($url[1])){
return URL::to($url[0]);
}
else{
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
}
add new url to your routes and assuming it will point to SomeController#SomeMethod, the SomeMethod should be something like :
public function SomeMethod(){
// get $data and $persons
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
I hope this helps
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)
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.
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;
}