If your app shows math, the formulas are probably stored as LaTeX, something like \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}, because that's what people already know how to type. The other format you'll run into is MathML, an XML version that browsers and screen readers understand.
To display either one, though, most sites load KaTeX or MathJax and let the browser draw the formulas. That works until a formula needs to be rendered somewhere without a browser, like an email or a Word document your app generates. At that point you're running Node next to PHP, or installing LaTeX on the server.
Phactorial, created by Dan Krieger, does the rendering in PHP. You give it TeX or MathML and get back a string of SVG, PNG, MathML, TeX, OMML (Word's equation format), or plain text. There's no Node process or headless browser to run, and you don't install fonts on the server, because the package ships with the STIX Two Math font.
It reads the same math commands as KaTeX, so formulas you already have stored for KaTeX should mostly render as-is. It also understands mhchem's \ce and \pu commands for chemical equations and units, and it accepts MathML with Word's mml: prefix or pasted from MathType and Wiris.
On a web page, you'll probably want SVG. Every glyph is drawn as a path, so the formula looks the same in every browser and doesn't need a web font. Email clients throw SVG away, which is what the PNG output (through Imagick) is for. OMML gives you equations you can put straight into a .docx file, and the plain-text version, x = (−b ± √(b² − 4ac))/(2a), is handy for alt text and search indexes.
You'll need PHP 8.4 with the ctype, dom, and mbstring extensions. It's still pre-1.0, so expect breaking changes, but it's worth trying if your app needs to put formulas in emails or documents.
Rendering TeX in Plain PHP
Install the core package:
composer require phactorial/phactorial
MathRender::fromTex() reads a TeX string. Call display() if the formula should sit on its own line, then pick an output format:
use Phactorial\MathRender; echo MathRender::fromTex('x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}') ->display() ->svg(pad: 1);
Without display(), the formula renders inline and lines up with the text baseline:
echo '<p>The area of a circle is ' . MathRender::fromTex('\pi r^2')->svg() . '.</p>';
The $...$ and \[...\] delimiters are optional, so you can pass whatever your database already has stored. svg() takes size, color, pad, and label. The color defaults to currentColor, so the formula uses the text color of the element it's in, and it follows your light and dark themes without extra CSS.
The SVG also comes with role="img" and an aria-label filled in from the plain-text version, so screen readers can read the formula aloud:
echo MathRender::fromTex('x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}')->svg(); // <svg role="img" aria-label="x = (−b ± √(b² − 4ac))/(2a)" …>
PNG, MathML, and Word Equations
For PNGs, you'll need Imagick. png() returns a MathPng object holding the bytes, the dimensions, and alt text, and it can write its own <img> tag. That's useful when you attach the image to an email and reference it by content ID:
$png = MathRender::fromTex('E = mc^2')->png(); echo $png->img('cid:formula-1');
There's a dataUri() method too, if you'd rather inline the image.
Any input format can go to any output format, so you can also use Phactorial to convert formulas. Say you're importing quiz questions that were written in Word and arrive as MathML, but your app stores everything as TeX:
$mathml = MathRender::fromTex('\sqrt{x^2 + 1}')->mathml(); // \frac{a}{b} $tex = MathRender::fromMathml('<math><mfrac><mi>a</mi><mi>b</mi></mfrac></math>') ->tex();
For Word, omml() returns a native equation. An inline one goes between runs in a paragraph, and a display one takes up a paragraph of its own:
$inline = MathRender::fromTex('a^2 + b^2 = c^2')->omml(); $block = MathRender::fromTex('\int_0^1 x\,dx = \tfrac12')->display()->omml();
The OMML output uses the m: and w: prefixes without declaring them, so your document's root element has to declare xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math".
Handling Formulas From Users
Bad TeX won't throw an exception. Phactorial draws as much as it can and keeps a list of notes about anything it dropped or approximated. If students type formulas into a form, check those notes and tell them when part of their answer didn't render:
use Phactorial\NoteLevel; $formula = MathRender::fromTex($userInput); foreach ($formula->notes() as $note) { if ($note->level === NoteLevel::Dropped) { // Part of the formula was not drawn. Tell the author. } }
Some commands aren't fully supported yet. \boxed, \cancel, and \tag are parsed but not drawn yet, and \colorbox, \fcolorbox, and siunitx commands like \SI and \qty aren't supported at all. You also can't get line breaks inside long formulas or numbered equations yet, which rules it out for some textbook-style content.
TeX input is capped at 16 KB, 256 levels of nesting, and 10,000 macro expansions. The docs suggest setting your own, much lower length limit on user input anyway, since a formula that gets close to those caps can turn into an SVG over a megabyte.
Markdown Support With CommonMark
A second package, phactorial/commonmark, adds math to League's CommonMark parser:
composer require phactorial/commonmark
Register MathExtension alongside the core extension:
use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use Phactorial\CommonMark\MathExtension; $environment = new Environment(['math' => ['output' => 'svg']]); $environment->addExtension(new CommonMarkCoreExtension()); $environment->addExtension(new MathExtension()); echo (new MarkdownConverter($environment))->convert('Area is $\pi r^2$.');
Single dollar signs mark inline math. A $$ block on its own lines, or a fenced code block tagged math, renders as display math, and \$ gives you a literal dollar sign. Prices like "costs $5 and $10" stay as text.
The options live under the math key:
| Key | Values | Default |
|---|---|---|
output |
svg, mathml |
svg |
size |
a number above 0 | 16 (pixels, SVG only) |
on_error |
source, render |
source |
latex_delimiters |
true, false |
false |
Using Phactorial in Laravel
Don't go looking for a service provider or a config file to publish, because there isn't one. The Laravel support is a set of recipes in the docs that add the CommonMark extension to the Markdown tools Laravel already has.
The quickest way to add it is Laravel's Str::markdown(), which accepts CommonMark options as its second argument and extensions as its third:
use Illuminate\Support\Str; use Phactorial\CommonMark\MathExtension; $html = Str::markdown( $post->body, ['math' => ['output' => 'mathml']], [new MathExtension()], );
The fluent str($post->body)->markdown() version takes the same arguments. You'll print the result with {!! $html !!}, so if your users write the Markdown, add 'html_input' => 'strip' to the options as well.
If you already render Markdown through Spatie's laravel-markdown package, it's two entries in config/markdown.php:
'commonmark_options' => [ 'math' => ['output' => 'mathml'], ], 'extensions' => [ Phactorial\CommonMark\MathExtension::class, ],
After that, <x-markdown> and the MarkdownRenderer class render math too. Spatie's package caches its output, and its syntax highlighter leaves math fences alone.
For a one-off formula in a Blade view, the docs suggest a small anonymous component in resources/views/components/math.blade.php:
@props(['tex', 'display' => false]) @php($math = \Phactorial\MathRender::fromTex($tex)) {!! ($display ? $math->display() : $math)->svg() !!}
Which you can then use anywhere:
<p>The area of a circle is <x-math tex="\pi r^2" />.</p> <x-math tex="\int_0^\infty e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}" display />
Formulas in Laravel Mail
Email needs the most setup. Gmail and Outlook both strip SVG, and Gmail blocks data: images, so neither the SVG output nor an inlined PNG will show up. For Markdown mail, the docs render each formula to a PNG file, store it, and link to it. Laravel reads mail Markdown extensions from config/mail.php:
'markdown' => [ 'extensions' => [ Phactorial\CommonMark\MathExtension::class, App\Markdown\EmailMath::class, ], ],
App\Markdown\EmailMath is a class you write, though the docs give you all of it to copy. It takes over rendering for math nodes and math fences, and the part that does the work looks like this:
$math = MathRender::fromTex($tex); $png = ($display ? $math->display() : $math)->png(pad: 1); $path = 'math/' . hash('sha256', $png->bytes) . '.png'; Storage::disk('public')->put($path, $png->bytes); $img = $png->img(Storage::disk('public')->url($path));
Naming each file after a hash of its bytes means you store a formula you send to ten thousand people once. Your mail templates don't change. You write math the same way you would anywhere else:
<x-mail::message> The area of a circle is $\pi r^2$. $$ \int_0^\infty e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2} $$ </x-mail::message>
Before you send anything, Imagick must be installed; you need to run php artisan storage:link, and APP_URL must be a public address because mail clients need absolute image URLs. Some clients also hide remote images until the reader allows them. Until they do, the reader sees the alt text, like πr².
Caching
By the project's own benchmarks, rendering is quick. A formula takes about 0.1 ms once the font is loaded, though the first one in a fresh PHP process takes about 15 ms without opcache. A page with 50 formulas comes in around 30 ms on the first render and under 10 ms after that. You can check those numbers on your own hardware with bin/benchmark.php in the repo.
Even so, there's no reason to re-render a blog post that hasn't changed. The docs cache the HTML under a hash of the post body:
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; use Phactorial\CommonMark\MathExtension; $html = Cache::remember( 'markdown:' . hash('xxh128', $post->body), now()->addWeek(), fn () => Str::markdown($post->body, [], [new MathExtension()]), );
Editing the post changes the key, so you never have to clear an entry manually after content changes. You do need to flush it after changing the math options or upgrading Phactorial, since the old HTML would otherwise stick around for a week.
The Phactorial docs have more recipes, including swapping in a different math font and building formulas in code with the Math builder. The source is on GitHub at One-Learning-Community/phactorial.