My initial controller code for Event is:
try {
$sales = $this->sales->create([
'customer_id' => $customer->id,
'sales_details' => json_encode($vData),
'total_price' => ((int)$data['q-rfh'] * (int)$data['p-rfh']) + ((int)$data['q-rfh-spro'] * (int)$data['p-rfh-spro']),
'created_by' => $user->username,
]);
\Event::fire('print.invoice', $sales);
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
]);
}
catch (\Exception $e) {
return \Response::json([
'type' => 'danger',
'message' => $e->getMessage(),
]);
}
I need to print the invoice using event because I need to return a response with ajax to let user know the sales has been successfully made.
The event code is as simple as this:
public function handle(SalesModel $sales) {
if ($sales) {
$data = [
'sales' => $sales,
];
$pdf = \PDF::loadView('invoice.sales', $data);
return $pdf->download('inv_' . Carbon::now() . '.pdf');
}
}
EventServiceProvider already listens to it:
protected $listen = [
'print.invoice' => [
'App\Events\InvoiceEventHandler',
],
];
Everything works fine, except that the PDF is not downloaded. I'm using https://github.com/barryvdh/laravel-dompdf
for creating and downloading the PDF. Can someone tell me what's wrong?
I give you and idea. Create the pdf file and store it at your server temporally
// return an absolute url
$pdfFile = \PDF::create('inv_' . Carbon::now() . '.pdf');
Now in your json response add the pdf file url in order to download it once the response arrives at client:
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
'pdf' => pdfFile
]);
From javascript, at success()
method you can call the pdf in other request