InvoiceController.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Invoice;
  5. use Illuminate\Http\Request;
  6. use Throwable;
  7. use ZipArchive;
  8. class InvoiceController extends Controller
  9. {
  10. public function downloadAllInvoices()
  11. {
  12. $zip = new ZipArchive;
  13. $zip_safe_path = storage_path('invoices.zip');
  14. $res = $zip->open($zip_safe_path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  15. $result = $this->rglob(storage_path('app/invoice/*'));
  16. if ($res === true) {
  17. $zip->addFromString('1. Info.txt', __('Created at').' '.now()->format('d.m.Y'));
  18. foreach ($result as $file) {
  19. if (file_exists($file) && is_file($file)) {
  20. $zip->addFile($file, basename($file));
  21. }
  22. }
  23. $zip->close();
  24. }
  25. return response()->download($zip_safe_path);
  26. }
  27. /**
  28. * @param $pattern
  29. * @param $flags
  30. * @return array|false
  31. */
  32. public function rglob($pattern, $flags = 0)
  33. {
  34. $files = glob($pattern, $flags);
  35. foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
  36. $files = array_merge($files, $this->rglob($dir.'/'.basename($pattern), $flags));
  37. }
  38. return $files;
  39. }
  40. /**
  41. * @param $paymentID
  42. * @param $date
  43. */
  44. public function downloadSingleInvoice(Request $request)
  45. {
  46. $id = $request->id;
  47. try {
  48. $query = Invoice::where('payment_id', '=', $id)->firstOrFail();
  49. } catch (Throwable $e) {
  50. return redirect()->back()->with('error', __('Error!'));
  51. }
  52. $invoice_path = storage_path('app/invoice/'.$query->invoice_user.'/'.$query->created_at->format('Y').'/'.$query->invoice_name.'.pdf');
  53. if (! file_exists($invoice_path)) {
  54. return redirect()->back()->with('error', __('Invoice does not exist on filesystem!'));
  55. }
  56. return response()->download($invoice_path);
  57. }
  58. }