The laravelqr subpackage installs a shared generator in your app, adds two view functions and
returns QR images from routes.
Install the package
import (
"github.com/bowerbird-si/laravel-go-qrcode"
"github.com/bowerbird-si/laravel-go-qrcode/laravelqr"
"go.laravel.com"
)
qr, err := laravelqr.New(
qrcode.Size(240),
qrcode.Margin(4),
)
if err != nil {
log.Fatal(err)
}
laravel.Run(laravel.Options{
Packages: []laravel.Package{qr},
// Routes, Views, …
})
The options you pass to laravelqr.New are the app's defaults. laravelqr.Package{} installs the plain
defaults.
In views
The package adds qrcode and qrcodeSrc to your templates:
<div>{{ qrcode .TicketURL }}</div>
<img src="{{ qrcodeSrc .TicketURL }}" alt="Ticket QR code">
qrcodeinlines an SVG element.qrcodeSrcreturns a PNGdata:URI for an<img src>.
Both take the text, then any qrcode.Option values to override the defaults for that one code. Pass
options in through your view data:
return web.View("ticket", map[string]any{
"TicketURL": url,
"Large": qrcode.Size(400),
}){{ qrcode .TicketURL .Large }}
The template helpers turn text into generated SVG geometry or encoded PNG bytes. Pass the original text to either helper.
As a response
laravelqr.Response renders a code with the app's defaults plus any extra options, and sets
Content-Type from the format:
router.Get("/ticket.png", func(r *web.Request) *web.Response {
response, err := laravelqr.Response(r.Context(), "https://example.com/tickets/42", qrcode.PNGFormat, qrcode.Size(300))
if err != nil {
return web.Fail(err)
}
return response
})| Format | Content-Type |
|---|---|
qrcode.SVGFormat | image/svg+xml |
qrcode.PNGFormat | image/png |
qrcode.EPSFormat | application/postscript |
The app's generator
laravelqr.From(ctx) returns the installed generator, for code that needs the bytes:
png, err := laravelqr.From(r.Context()).PNG("https://example.com/tickets/42")
Call From with an application context after installing the package. It uses Laravel’s service lookup.
In email
Attach the PNG as an inline image and refer to it by content ID:
png, err := laravelqr.From(r.Context()).PNG("https://example.com/tickets/42")
if err != nil {
return err
}
return mail.To(guest).Send(r.Context(), mail.Message{
Subject: "Your ticket",
HTML: `<p>Show this code at the door:</p><img src="cid:ticket-qr" alt="Ticket QR code">`,
Inline: map[string]mail.Attachment{"ticket-qr": mail.AttachData(png, "ticket.png")},
})
Use PNG in email: many mail clients don't show SVG or data: URIs.