Laravel: Using the *new* Markdown parser the easy way

I am altering the deal. Pray I don’t alter it any further.

Photo by Artem Sapegin on Unsplash

It has been a long time since I wrote about the Markdown Parser. In a nutshell, Laravel includes a package responsible to convert Markdown text to HTML, which is used to renders mails automatically by the framework.

A lot has changed since then, mainly the package managing Markdown has been changed from Parsedown to Commonmark, the latter coming from the guys of The PHP League. Yeah, the same guys that created Flysystem.

Using the parser the “safe way”

There are two ways of using the Markdown parser. The first, and most “safe” way to do it is to call the same Markdown parser used for Emails, which is located Illuminate\Mail\Markdown.

This class has an static method called parse which accepts the Markdown text to be parsed to HTML, and returns a very convenient HtmlString instance.

For example, let’s use it inside a Controller action: when the user inputs Markdown, we will parse it and return the corresponding HTML string:

Using this way (calling the Markdown parser directly instead of the underlying class), allows to leverage for any internal code changes inside the framework, specially those who change the Markdown package.

The second way is less safe, and means using Parsedown or Commonmark directly. This allows better control on how the text is parsed, since the Mail’s parse() method doesn’t accepts options to be passed to the Markdown parser itself.

If you are going for the second option, I humbly suggest you include one of these packages explicitly in your project’s composer.json, since the framework may change the parser in the future for something better, which may leave your code unusable:

composer require vendor/markdown-package

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store