How to implement torchlight with Laravel(+Fliament Markdown)

I have always wanted to highlight code blocks on my blog post. So I started to search and found out some solutions. The first thing that I found was Prism.js, which is dedicated framework for code highlighting in frontend. I've added prismjs package in my package.json file and implemented using vite and bun. The result was not bad, but I was wondering how can I get something like in Github or Laravel document. Then I saw some comment on blog post about torchlight api. It is blazingly fast, and no need additional js framework.

The instructions for the installation was well documented on their official website. However, applying Torchlight to Markdown data retrieved from the database, instead of hardcoding it into a Blade template, was more challenging than I expected. It was very difficult to find well-organized resources on this topic, so I decided to document the process myself.

  1. Installing the CommonMark PHP Client I use Filament Admin to write blog posts. This admin panel supports a Markdown editor, which makes it convenient to create posts easily. To enable Torchlight to recognize and convert this Markdown data, the CommonMark PHP Client is required. Although the installation process is well-documented here, the issue arises when using Laravel 11. Installing via Composer fails due to dependency conflicts with the current version. I discovered that someone already made a PR for Laravel 11, but it was not merged at this time. We can define the installation source manually in the composer.json file. I forked the repository and added its URL as well. It will automatically install the torchlight Laravel Client too. Since Laravel Client has no problem with Laravel 11, there shouldn't be any compatibility issues with installing it.
...
"torchlight/torchlight-commonmark": "dev-main"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/USERNAME/torchlight-commonmark-php.git"
}
]
...
  1. Adding a new attribute in the Model class. This stage is a bit tricky, and I spent a lot of time on it. From now on, if you use tag, the Torchlight API would work correctly. However, the Torchlight API is still cannot process our Markdown data. We need to add an attribute to our model for this.
public function getMarkdownAttribute()
{
$environment = new Environment();
 
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addExtension(new GithubFlavoredMarkdownExtension());
$environment->addExtension(new TorchlightExtension());
 
$converter = new MarkdownConverter($environment);
 
return $converter->convert($this->content);
 
}

Done! We can apply some theme you like as well.