> ## Documentation Index
> Fetch the complete documentation index at: https://docs.linkx.tr/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate QR Codes with the Laravel QrCode Facade API

> Use the QrCode facade's fluent, immutable builder API to generate, style, and export QR codes anywhere in your Laravel application.

The `QrCode` facade is the primary way to generate QR codes in PHP code — controllers, jobs, service classes, and Artisan commands. It exposes a fluent builder so you can chain options before calling `generate()`, and every call inherits the global defaults you set in `config/qrcode.php`.

## Import the facade

Add the facade import at the top of any file that generates QR codes:

```php theme={null}
use Linkxtr\QrCode\Facades\QrCode;
```

## Basic generation

`generate()` accepts a string payload and returns a `QrCodeResult` object. `QrCodeResult` implements `Stringable`, so you can cast it directly to a string to get the raw SVG markup (or binary data for PNG/WebP).

```php theme={null}
// Returns a QrCodeResult (Stringable)
$result = QrCode::generate('https://example.com');

// Cast to string to get the SVG markup
$svg = (string) $result;
```

### Save to a file

Pass a second argument — an absolute file path — to write the output directly to disk. The directory must already exist and be writable.

```php theme={null}
QrCode::generate(
    'https://example.com',
    storage_path('app/qrcodes/example.svg')
);
```

> [!WARNING]
>
> `generate()` throws `CannotWriteFileException` if the target directory does
> not exist or the process lacks write permission. Create the directory first or
> catch the exception explicitly.

## Fluent builder chaining

Every method on the `QrCode` facade returns a new immutable instance, so you can chain calls freely without mutating global state.

```php theme={null}
$qrCode = QrCode::size(300)
    ->format('png')
    ->color(255, 0, 0)          // red foreground
    ->backgroundColor(255, 255, 255)
    ->margin(2)
    ->errorCorrection('H')
    ->generate('https://example.com');
```

> [!TIP]
>
> Because the builder is immutable, you can create a "base" generator once and reuse it for different payloads without side effects:
>
> ```php theme={null}
> $base = QrCode::size(400)->format('png')->color(0, 102, 204);
>
> $qr1 = $base->generate('https://example.com');
> $qr2 = $base->generate('https://laravel.com');
> ```

## Builder method reference

**size** `int`

Width and height of the QR code in pixels. The config default is `400`.

**format** `string`

Output format: `svg`, `png`, `webp`, or `eps`. The config default is `svg`.
PNG and WebP require `ext-imagick` or `ext-gd`. EPS requires no extensions.

**color** `int, int, int, int|null`

Foreground color. In RGB mode (default): `color(red, green, blue, alpha?)`
where each channel is `0–255` and alpha is `0–100`. In CMYK mode: `color(cyan,
    magenta, yellow, black)` on a `0–100` scale.

**backgroundColor** `int, int, int, int|null`

Background color. Accepts the same arguments as `color()`.

**margin** `int`

Quiet-zone margin around the QR code. The config default is `4`.

**errorCorrection** `string`

Error correction level: `L` (7 %), `M` (15 %), `Q` (25 %), or `H` (30 %). The
config default is `M`.

**encoding** `string`

Character encoding for the payload, e.g. `UTF-8`. The config default is
`UTF-8`.

**style** `string`

Module (dot) shape: `square`, `dot`, or `round`.

**eye** `string`

Finder-pattern eye style: `square`, `circle`, or `pointy`.

**internalEye** `string`

Inner eye style for composite eye patterns: `square`, `circle`, or `pointy`.

**gradient** `array, array, string`

Gradient fill across the QR code modules. Pass start and end colors as RGB
arrays and a direction: `vertical` or `horizontal`.

**merge** `string, float`

Overlay an image (e.g. a logo) at the center. Pass a file path and an optional
size percentage (default `0.2` = 20 %). Supported for SVG, PNG, and WebP —
**not** EPS.

**mergeString** `string, float`

Overlay an image passed as raw binary string content instead of a file path.
Accepts the image content and an optional size percentage (default `0.2` = 20
%). Use this when the image is already loaded into memory rather than stored
on disk.

**cmyk** `void`

Switch the color model to CMYK. Use `0–100` integer values for each channel.

**rgb** `void`

Switch the color model back to RGB (the default). Use `0–255` integer values
per channel.

**gray** `int, int|null`

Set a grayscale palette. `0` is black, `100` is white. Optionally pass a
second value for the background gray level.

## Output formats

```php SVG (default) theme={null}
$svg = (string) QrCode::generate('https://example.com');
// $svg contains raw <svg>…</svg> markup
```

```php PNG theme={null}
$png = (string) QrCode::format('png')->generate('https://example.com');
// $png contains raw PNG binary data
```

```php WebP theme={null}
$webp = (string) QrCode::format('webp')->generate('https://example.com');
// $webp contains raw WebP binary data
```

```php EPS theme={null}
$eps = (string) QrCode::format('eps')->generate('https://example.com');
// $eps contains Encapsulated PostScript text
```

## Using the facade in Blade templates

`QrCodeResult` is `Stringable` and its string value contains raw SVG markup (or binary data). Use the **unescaped** output directive `{!! !!}` so Laravel does not HTML-encode the angle brackets:

```blade theme={null}
{{-- ✅ Correct — renders the SVG inline --}}
{!! QrCode::generate('https://example.com') !!}

{{-- ❌ Wrong — HTML-encodes < and > so the browser shows raw text --}}
{{ QrCode::generate('https://example.com') }}
```

> [!NOTE]
>
> For Blade templates, prefer the `<x-qr-code>` component instead — it handles escaping, accessibility attributes, and PNG/WebP base64 embedding automatically. See [Blade Component](https://docs.linkx.tr/usage/blade-component.md).

## Returning a QR code from a controller

`QrCodeResult` implements Laravel's `Responsable` interface. You can return the result object directly from any controller method, and Laravel automatically invokes `toResponse()` to return an HTTP 200 response with the correct `Content-Type` header (such as `image/svg+xml` or `image/png`).

> [tab] Automatic Responsable
>
> ```php theme={null}
> use Linkxtr\QrCode\Facades\QrCode;
> use Linkxtr\QrCode\Support\QrCodeResult;
>
> public function show(): QrCodeResult
> {
>     // Returns HTTP 200 with automatic Content-Type: image/svg+xml
>     return QrCode::size(300)->generate('https://example.com');
> }
> ```

> [tab] Custom headers & HTTP caching
>
> ```php theme={null}
> use Illuminate\Http\Request;
> use Illuminate\Http\Response;
> use Linkxtr\QrCode\Facades\QrCode;
>
> public function show(Request $request): Response
> {
>     $result = QrCode::size(300)->generate('https://example.com');
>
>     $response = $result->toResponse($request);
>     $response->setEtag(md5((string) $result));
>     $response->header('Cache-Control', 'public, max-age=86400, immutable');
>     $response->isNotModified($request);
>
>     return $response;
> }
> ```

> [tab] File download
>
> ```php theme={null}
> use Illuminate\Http\Response;
> use Linkxtr\QrCode\Facades\QrCode;
>
> public function download(): Response
> {
>     $path = storage_path('app/qrcodes/qr.png');
>
>     QrCode::size(400)
>         ->format('png')
>         ->generate('https://example.com', $path);
>
>     return response()->download($path, 'qrcode.png');
> }
> ```

## Caching generated QR codes

Rendering complex vector or raster QR codes with high error correction and merged logos consumes CPU cycles. The `cache()` method caches generated output in your application's cache store, avoiding redundant rendering for identical requests.

```php theme={null}
use Carbon\Carbon;
use DateInterval;
use Linkxtr\QrCode\Facades\QrCode;

// Cache for 3600 seconds (1 hour)
QrCode::cache(3600)->generate('https://example.com');

// Cache with a Carbon DateTime instance (e.g., until midnight)
QrCode::cache(Carbon::tomorrow())->generate('https://example.com');

// Cache with DateInterval (e.g., 2 hours)
QrCode::cache(new DateInterval('PT2H'))->generate('https://example.com');

// Explicitly bypass cache for one-time tokens or dynamic OTPs
QrCode::withoutCache()->generate('https://example.com');
```

> [!TIP]
>
> Cache keys are generated deterministically from the payload and serialized generator configuration. If you change any parameter (such as size, color, or error correction), the package automatically generates and caches a new QR code.

## Styled QR code examples

```php Brand colors theme={null}
QrCode::size(300)
    ->color(58, 94, 255)           // blue modules
    ->backgroundColor(255, 255, 255)
    ->style('dot')
    ->eye('circle')
    ->generate('https://example.com');
```

```php Gradient theme={null}
QrCode::size(300)
    ->gradient([0, 0, 255], [255, 0, 0], 'vertical')
    ->generate('https://example.com');
```

```php Logo overlay (PNG) theme={null}
QrCode::size(400)
    ->format('png')
    ->errorCorrection('H')         // use H when merging a logo
    ->merge(public_path('logo.png'), 0.3)
    ->generate('https://example.com');
```

```php CMYK print output (EPS) theme={null}
QrCode::size(400)
    ->format('eps')
    ->cmyk()
    ->color(100, 50, 0, 10)        // cyan, magenta, yellow, black
    ->backgroundColor(0, 0, 0, 0)
    ->generate('https://example.com');
```

## Config-driven defaults

When you resolve the `QrCode` facade, the package automatically reads `config/qrcode.php` and uses those values as defaults. Any method you chain overrides only that specific option for the current chain.

```php theme={null}
// config/qrcode.php sets size=400, format=svg, margin=4, error_correction=M
// The chain below only overrides color — everything else comes from config
QrCode::color(0, 102, 204)->generate('https://example.com');
```

Publish the config file to customise the global defaults:

```bash theme={null}
php artisan vendor:publish --tag=qrcode-config
```

> [!NOTE]
>
> Config defaults apply when you use the facade, the Blade component, or resolve
> `Linkxtr\QrCode\Generator` from the service container. If you instantiate `new
>     Generator()` directly, you get hardcoded package defaults unless you pass the
> config array yourself.

## Built-in data-type helpers

The facade includes helpers for common structured payloads. Each returns a `QrCodeResult` just like `generate()`.

> [card] BTC
>
> ```php theme={null}
> QrCode::BTC(
>     'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq',
>     0.001
> );
> ```

> [card] Email
>
> ```php theme={null}
> QrCode::Email(
>     'hello@example.com',
>     'Subject',
>     'Body text'
> );
> ```

> [card] WiFi
>
> ```php theme={null}
> QrCode::WiFi([
>     'ssid'       => 'MyNetwork',
>     'encryption' => 'WPA2',
>     'password'   => 's3cr3t',
> ]);
> ```

> [card] vCard
>
> ```php theme={null}
> QrCode::VCard([
>     'name'  => 'Jane Doe',
>     'email' => 'jane@example.com',
>     'phone' => '+1234567890',
>     'url'   => 'https://example.com',
> ]);
> ```

> [card] Geo
>
> ```php theme={null}
> QrCode::Geo(37.7749, -122.4194);
> ```

> [card] SMS
>
> ```php theme={null}
> QrCode::SMS('+1234567890', 'Hello!');
> ```

> [card] WhatsApp
>
> ```php theme={null}
> QrCode::WhatsApp([
>     'number'  => '+1234567890',
>     'message' => 'Hi there!',
> ]);
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.