PHP code example of bitdreamit / laravel-qz-tray
1. Go to this page and download the library: Download bitdreamit/laravel-qz-tray library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bitdreamit / laravel-qz-tray example snippets
DB::table('qz_print_jobs')->latest()->first(); // the test job is there
// routes/web.php — a normal, protected mPDF route. Nothing special.
Route::get('/receipt/{id}.pdf', [ReceiptController::class, 'pdf'])->middleware('auth');
public function pdf(Request $request, $id)
{
$pdf = \Mpdf\Mpdf::loadView('receipts.show', compact('id'));
return $pdf->stream('receipt-'.$id.'.pdf'); // ->download() works identically
}
// routes/web.php — a completely normal Laravel route
Route::get('/invoices/{invoice}/pdf', function (Invoice $invoice) {
return \Mpdf\Mpdf::loadView('invoices.pdf', compact('invoice'))
->stream('invoice-'.$invoice->number.'.pdf');
})->name('invoices.pdf')->middleware('auth');
Route::get('/api/labels/{product}/zpl', function (Product $product) {
$zpl = "^XA\n^FO50,50^ADN,36,20^FD{$product->name}^FS\n"
. "^FO50,100^BCN,80,Y,N,N^FD{$product->barcode}^FS\n^XZ";
return response($zpl, 200, ['Content-Type' => 'text/plain']);
});
// JS side — one line:
printUrl('/api/labels/7/zpl', { type: 'zpl', printer: 'Zebra ZD420' });
public function receipt(Order $order)
{
$out = "\x1B\x40\x1B\x61\x01" . $order->store_name . "\n\x1B\x61\x00";
foreach ($order->items as $item) {
$out .= str_pad($item->name, 24) . str_pad('$'.$item->price, 8, ' ', STR_PAD_LEFT) . "\n";
}
$out .= "\n\n\n\x1D\x56\x41";
return response($out, 200, ['Content-Type' => 'application/octet-stream']);
}
// Controller — after the order is created:
return redirect()->route('orders.show', $order)
->with('auto_print', route('orders.pdf', $order));
return [
// Paths where the signing certificate and key live (never web-accessible)
'cert_path' => storage_path('qz/digital-certificate.txt'),
'key_path' => storage_path('qz/private-key.pem'),
'cert_ttl' => 3600, // seconds the browser may cache the cert
// Certificate generation defaults
'certificate' => [
'validity_days' => 7300, // ~20 years
'algorithm' => 'sha256',
'key_bits' => 2048,
'subject' => [
'countryName' => 'US',
'organizationName' => 'My Company',
'commonName' => 'My App QZ Tray',
'emailAddress' => '[email protected] ',
],
],
// Auto-generate on first boot (dev convenience; use artisan commands in production)
'auto_generate_cert' => env('QZ_AUTO_GENERATE_CERT', false),
// Allow HTTP endpoint to (re)generate the cert — keep OFF in production
'allow_public_cert_generate' => env('QZ_ALLOW_PUBLIC_CERT_GENERATE', false),
// Default printer (optional — users pick via the switcher otherwise)
'default_printer' => env('QZ_DEFAULT_PRINTER'),
'allow_printer_switch' => true,
'remember_printer_per_page' => true, // memory per URL path
'printer_cache_duration' => 86400, // 24h server-side cache
// Which identity wins when several match: 'device' first is correct for
// shared/kiosk workstations (the MACHINE picks the printer). Use
// ['user', 'device', 'session'] if the printer should follow the person.
'identity_priority' => ['device', 'user', 'session'],
// Primary-key type for qz_print_jobs — set BEFORE first migrate.
'id_type' => env('QZ_JOB_ID_TYPE', 'uuid'), // 'uuid' | 'bigint'
// 'v7' = time-ordered UUID (much better index locality than v4 for a
// write-heavy table). Falls back to v4 on Laravel 10 automatically.
'uuid_version' => env('QZ_UUID_VERSION', 'v7'),
// QZ Tray WebSocket connection (client-side)
'websocket' => [
'host' => env('QZ_WEBSOCKET_HOST', 'localhost'),
'port' => env('QZ_WEBSOCKET_PORT', 8181),
'retries' => 1,
'timeout' => 10,
],
// Browser fallback when the tray is not running (classic layer)
'fallback' => [
'enabled' => true,
'open_in_new_tab' => true,
'show_warning' => true,
],
// Keyboard shortcut that opens the printer switcher (Ctrl+Shift+P)
'hotkey' => [
'enabled' => true,
'combination' => 'ctrl+shift+p',
],
// Route configuration — ADD 'auth' IN PRODUCTION
'routes' => [
'prefix' => 'qz',
'middleware' => ['web'],
'throttle' => '60,1',
],
// Optional request-level logging to your Laravel log channel
'logging' => [
'enabled' => env('QZ_LOGGING_ENABLED', false),
'channel' => env('QZ_LOGGING_CHANNEL', 'stack'),
'level' => env('QZ_LOGGING_LEVEL', 'info'),
],
// Auto-tag every print/preference with a tenant id (see Multi-Tenant)
// 'tenant_id_resolver' => fn ($request) => auth()->user()?->tenant_id,
];
// routes/console.php (Laravel 11+) or app/Console/Kernel.php
Schedule::command('qz:prune-preferences --older-than=90')->weekly();
Schedule::command('qz:prune-jobs --older-than=30')->weekly();
// config/qz-tray.php
'tenant_id_resolver' => fn ($request) => auth()->user()?->tenant_id,
// or with stancl/tenancy:
'tenant_id_resolver' => fn ($request) => tenant('id'),
// POST /qz/print or POST /qz/printer
['tenant_id' => '482', // id_type = bigint
'project_id' => 'b2b1f6c0-3b3d-4c9a-9e2e-1a2b3c4d5e6f'] // id_type = uuid
$jobs = DB::table('qz_print_jobs')
->where('tenant_id', auth()->user()->tenant_id)
->where('status', 'completed')
->orderByDesc('created_at')
->paginate(20);
// 1. Protect all /qz/* routes with auth:
// config/qz-tray.php
'routes' => [
'prefix' => 'qz',
'middleware' => ['web', 'auth'], // ← add in production
'throttle' => '60,1', // signing endpoint rate limit
],
// extra middleware is fine too: ['web', 'auth', 'verified', 'role:printer']
// 3. Never enable in production:
'allow_public_cert_generate' => false,
bash
php artisan qz:install
bash
php artisan qz:install --force # re-install, overwriting previously published files
php artisan qz:install --no-cert # publish everything but skip certificate generation
bash
php artisan migrate
bash
php artisan qz:doctor
blade
<script>
window.QZ_CONFIG = {
tenantId: '{{ auth()->user()?->tenant_id }}',
// or: projectId: '{{ $project->id }}',
};
</script>
bash
php artisan qz:generate-ca
php artisan qz:generate-certificate --force --ca --domain=*.yourdomain.com,yourdomain.com
php artisan qz:client-bundle --zip
js
// once, after smart-print.js is loaded:
SmartPrint.define({
printLabReceipt: { type: 'pdf', profile: 'a4' },
printLabReceipts: { type: 'pdf', profile: 'a4' },
printWorkList: { type: 'pdf', profile: 'small', printer: 'receipt' },
printLabel: { type: 'pdf', profile: 'label', printer: 'label' },
});
SmartPrint.aliasPrinter('receipt', 'XP-80C'); // friendly name → real OS printer name
SmartPrint.aliasPrinter('label', 'Zebra GK420d');
printLabReceipt('/receipt/5.pdf'); // now a real function everywhere
blade
{{-- resources/views/invoices/show.blade.php --}}
<div class="invoice-actions">
<button class="smart-print" data-qz-url="{{ route('invoices.pdf', $invoice) }}">
🖨 Print Invoice #{{ $invoice->number }}
</button>
<button class="smart-print" data-qz-url="{{ route('invoices.pdf', $invoice) }}"
data-qz-copies="2" data-qz-printer="Office HP LaserJet">
🖨 Print 2 Copies
</button>
</div>
html
<script>window.QZ_CONFIG = { tenantId: '{{ auth()->user()?->tenant_id }}' };</script>
bash
php artisan qz:clear-cache --all
php artisan qz:prune-preferences --older-than=0
php artisan cache:clear && php artisan config:clear
bash
composer update bitdreamit/laravel-qz-tray
php artisan optimize:clear
php artisan vendor:publish --tag=qz-assets --force # the new smart-print.js
bash
composer update bitdreamit/laravel-qz-tray
php artisan vendor:publish --tag=qz-assets --force
php artisan vendor:publish --tag=qz-config --force
php artisan qz:generate-certificate --force
php artisan migrate