I'm building out a Shedquarters in my backyard! Check out the ever-evolving post + pictures here →

Blogging with Markdown in Laravel

April 8, 2021

Like every good developer, I've rebuilt my personal site many, many times over the years. Way too many times. I've finally settled on a stack that is fast, simple, and (I think) beautiful.

My setup is extremely straightforward: it's a plain 'ol Laravel app, markdown files, and the league/commonmark extension. No database, no JavaScript.

It's hosted on Laravel Vapor so I never even have to worry about servers. It's all deployed straight from a GitHub action, so I can just write a post and git push and it's live to the world.

I used Tighten's Jigsaw for a while and really liked it. I used to build and push the whole site to a static S3 bucket, but ever since Vapor came around I don't really worry about hosting anymore so I prefer to not have a build step and the full power of Laravel if I need it.

Writing the Articles

All of my articles are stored as markdown files in the resources/views/articles directory.

Screenshot of my filesystem

I write them all in standard markdown. For example, here's the previous section up until now:

1## Writing the Articles
2 
3All of my articles are stored as markdown files in the `resources/views/articles` directory.
4 
5![Screenshot of my filesystem](/images/articles/markdown.png){.mx-auto .max-w-100 .rounded .border .shadow}
6 
7I write them all in standard markdown. For example, here's the previous section up until now:
Code highlighting powered by torchlight.dev.

I use a couple of markdown extensions (covered below), but the bulk of the work is done by the league/commonmark package. I use Graham Campbell's wrapper around it, because it gives you a few nice Laravel-specific options.

Storing Articles in Sushi

As I mentioned above, I have no database on this site. It's very nice because it keeps everything stupidly simple. I do like being able to work with the posts as an Eloquent collection though, so I've pulled in Caleb Porzio's Sushi pacakge, which bills itself as "Eloquent's missing array driver."

Sushi is great because you just define a rows property, fill it up with your records, and then you can do your normal Eloquent operations on it like Article::first().

Here's the Article.php from this app (rows 23 - 139 are collapsed, click to expand):

app/Article.php

1<?php
2namespace App;
3 
4use Illuminate\Database\Eloquent\Model;
5 
6class Article extends Model
7{
8 use \Sushi\Sushi;
9 
10 protected $casts = [
11 'date' => 'date',
12 ];
13 
14 protected static function boot()
15 {
16 parent::boot();
17 
18 static::addGlobalScope('order', function ($query) {
19 $query->orderBy('date', 'desc');
20 });
21 }
22 
23 protected $rows = [[ ...
24 'title' => 'Carving the Statue of David',
25 'date' => '2013-01-30',
26 'path' => '2013/carving-the-statue',
27 'description' => '',
28 ], [
29 'title' => 'Idea Extraction Gone Terribly Wrong',
30 'date' => '2013-02-06',
31 'path' => '2013/idea-extraction-gone-terribly-wrong',
32 'description' => '',
33 ], [
34 'title' => 'How I Use Evernote and IFTTT',
35 'date' => '2013-02-26',
36 'path' => '2013/how-i-use-evernote-and-ifttt',
37 'description' => '',
38 ], [
39 'title' => 'Yii, Heroku, and The Asset Pipeline',
40 'date' => '2013-04-09',
41 'path' => '2013/yii-heroku-and-the-asset-pipeline',
42 'description' => '',
43 ], [
44 'title' => 'Importing Transactions Into Mint',
45 'date' => '2013-04-11',
46 'path' => '2013/importing-transactions-into-mint',
47 'description' => '',
48 ], [
49 'title' => 'Wrangling Timezones in PHP, MySQL, and Yii',
50 'date' => '2013-04-21',
51 'path' => '2013/wrangling-timezones-in-php-mysql-and-yii',
52 'description' => '',
53 ], [
54 'title' => 'Automating Yii Migrations on Heroku',
55 'date' => '2013-05-02',
56 'path' => '2013/automate-yii-migrations-in-heroku',
57 'description' => '',
58 ], [
59 'title' => 'Scheduling Jobs With Yii',
60 'date' => '2013-05-06',
61 'path' => '2013/scheduling-jobs-with-yii',
62 'description' => '',
63 ], [
64 'title' => 'Yii and the Asset Pipeline: Part 2',
65 'date' => '2013-06-19',
66 'path' => '2013/yii-and-the-asset-pipeline-part-2',
67 'description' => '',
68 ], [
69 'title' => 'Using MySQL Triggers to Ensure Immutability',
70 'date' => '2013-06-26',
71 'path' => '2013/using-mysql-triggers-to-ensure-immutability',
72 'description' => '',
73 ], [
74 'title' => 'Encrypting and Encoding Information in URLs with PHP',
75 'date' => '2013-09-26',
76 'path' => '2013/encrypting-and-encoding-information-in-urls-with-php',
77 'description' => '',
78 ], [
79 'title' => 'Remaking "Snake" In Excel',
80 'date' => '2013-07-09',
81 'path' => '2013/remaking-cellphone-snake-in-microsoft-excel',
82 'description' => '',
83 ], [
84 'title' => 'My Aperture Backup Strategy',
85 'date' => '2013-09-09',
86 'path' => '2013/my-aperture-backup-strategy',
87 'description' => '',
88 ], [
89 'title' => 'Hosting An Advanced Yii2 App on Heroku',
90 'date' => '2014-01-10',
91 'path' => '2014/hosting-an-advanced-yii2-application-on-heroku',
92 'description' => '',
93 ], [
94 'title' => 'Introducing Vue Model',
95 'date' => '2016-06-08',
96 'path' => '2016/introducing-vue-model',
97 'description' => '',
98 ], [
99 'title' => 'Laravel Pseudo-Daemons',
100 'date' => '2020-05-17',
101 'path' => '2020/laravel-pseudo-daemons',
102 'description' => "The thought of adding each new daemon in Forge, making sure it was killed on deploy, and communicating to the team which commands were daemons sounded like something I didn't want to take on.",
103 ], [
104 'title' => 'Realtime Spreadsheets with Laravel',
105 'date' => '2020-08-27',
106 'path' => '2020/laravel-realtime-spreadsheets',
107 'description' => 'An article about using Laravel together with Handsontable.',
108 ], [
109 'title' => 'Ensuring Consistent Polymorphic Relationships with Laravel',
110 'date' => '2020-10-26',
111 'path' => '2020/laravel-consistent-morphs',
112 'description' => "Tips to ensure consistency when using Laravel's polymorphic relationships.",
113 ], [
114 'title' => 'Handling Large CSVs with Laravel',
115 'date' => '2020-10-28',
116 'path' => '2020/large-csvs-with-laravel',
117 'description' => "Strategies I've developed over the past couple of years that I think might be helpful if you're handling large CSVs.",
118 ], [
119 'title' => 'Building a Shedquarters in My Backyard',
120 'date' => '2021-01-20',
121 'path' => 'shed',
122 'description' => 'Building a shedquarters in my backyard during a pandemic.',
123 ], [
124 'title' => 'Is Making Software Sisyphean?',
125 'date' => '2021-01-14',
126 'path' => '2021/is-making-software-sisyphean',
127 'description' => 'Sisyphus, cursed by Zeus to roll a boulder up a hill for all eternity. Is that us?',
128 ], [
129 'title' => 'Fixing "Laravel PackageManifest.php: Undefined index: name" in GitHub Actions',
130 'date' => '2021-01-26',
131 'path' => '2021/fixing-laravel-package-manifest-php-undefined-index-name',
132 'description' => 'Fixing an error caused by Composer 2.',
133 ],[
134 'title' => 'Reliably Building Frontend Assets With NVM and Yarn (or NPM)',
135 'date' => '2021-02-24',
136 'path' => '2021/reliably-building-frontend-assets-with-nvm-and-yarn-or-npm',
137 'description' => "Generating reproducible asset bundles without losing your mind."
138 ], [
139 'title' => 'Blogging with Markdown in Laravel',
140 'date' => '2021-04-08',
141 'path' => '2021/blogging-with-markdown-in-laravel',
142 'description' => "Writing beautiful and simple blogs with Markdown in Laravel."
143 ]];
144 
145 public function getYearAttribute()
146 {
147 $year = $this->date->format('Y');
148 
149 if ($year < 2020) {
150 return 'Much (Much) Older';
151 }
152 
153 return $year;
154 }
155}

Routing

To route web requests to the articles, I have an extremely open catch-all route at the end of my web.php file:

web.php

1Route::get('/{any?}', 'ViewController@show')->where([
2 'any' => '.+',
3]);

This is my last defined route, and it matches basically anything. It sends requests into a ViewController that checks within the views folder to see if there is a *.blade.php file that matches the request, and if not, it will check the articles folder to see if it finds one there.

ViewController.php

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Article;
6 
7class ViewController extends Controller
8{
9 protected $disk;
10 
11 public function __construct()
12 {
13 $this->disk = Storage::disk('views');
14 }
15 
16 public function show($view = 'index')
17 {
18 if ($this->disk->exists($view.'.blade.php')) {
19 return view($view, [
20 'view' => $view,
21 ]);
22 }
23 
24 return $this->article($view);
25 }
26 
27 public function article($view)
28 {
29 $article = Article::where('path', $view)->first();
30 
31 if (!$article) {
32 return 0;
33 }
34 
35 return view('_post', [
36 'view' => 'articles/' . $view,
37 'article' => $article,
38 'title' => $article->title,
39 'date' => $article->date,
40 ]);
41 }
42}

See on line 29 that we can use standard Eloquent methods against an array of records, thanks Sushi!

Heading Links

You may be familiar with the little hashtags # next to each header from either GitHub READMEs, Laravel's documentation, or any number of other places. These function as anchor links so that you can link to a particular part of a document.

Go ahead, try clicking the one a few lines up!

These are fantastic to have, but a pain to manually keep up to date, so I use a commonmark extension for this.

In my markdown.php file, I have several extensions defined, but the one we want to look at right now is the HeadingPermalinkExtension.

config/markdown.php

1'extensions' => [
2 // Torchlight syntax highlighting
3 TorchlightExtension::class,
4 
5 // The location of our static assets varies based on wherever
6 // Vapor puts them. This will point them to the right spot.
7 VaporAssetWrapping::class,
8 
9 // Add `#` and links to headers.
10 HeadingPermalinkExtension::class,
11 
12 // Add attributes straight from markdown.
13 AttributesExtension::class
14],
15 
16'heading_permalink' => [
17 'html_class' => 'permalink',
18 'id_prefix' => 'user-content',
19 'insert' => 'before',
20 'title' => 'Permalink',
21 'symbol' => '#',
22],

This extension is one of the default ones provided by The League itself, so there is nothing else to install.

You can configure the symbol, along with several other attributes just by passing through your preferred configuration into heading_permalink.

As for styling, I just went through and manually adjusted the margin so that they would all line up nicely:

app.css

1.permalink {
2 @apply text-gray-300 absolute font-light no-underline;
3 
4 &:hover {
5 @apply text-gray-600;
6 }
7}
8 
9h1 .permalink { margin-left: -33px; }
10h2 .permalink { margin-left: -28px; }
11h3 .permalink { margin-left: -22px; }
12h4 .permalink { margin-left: -22px; }
13h5 .permalink { margin-left: -19px; }
14h6 .permalink { margin-left: -18px; }

Code Highlighting

For code highlighting, I'm using a service that I built called Torchlight.

Over the years I've tried Prism JS, Highlight JS, along with a few other that I've since forgotten. I finally decided to build my own exactly the way I wanted, once and for all.

There were a lot of things I wanted from a highlighter, and Torchlight has it all:

  • Uses the VS Code tokenizer, so it gets everything right, even the wacky stuff.
  • Supports all VS Code themes, even random ones you find online
  • Requires no JavaScript
  • Requires no external CSS
  • Is lightning fast
  • Supports git-style diffing
  • Supports line numbers, line highlight, line focusing
  • Supports collapsing code blocks, again, without JavaScript

All it takes to set up is to get an API token and install the commonmark extension.

config/markdown.php

1'extensions' => [
2 // Torchlight syntax highlighting
3 TorchlightExtension::class,
4 
5 // The location of our static assets varies based on wherever
6 // Vapor puts them. This will point them to the right spot.
7 VaporAssetWrapping::class,
8 
9 // Add `#` and links to headers.
10 HeadingPermalinkExtension::class,
11 
12 // Add attributes straight from markdown.
13 AttributesExtension::class
14],

That's it! No JavaScript to set up, no CSS theme files to add, nothing.

If you want to change the theme, you can do so in the config file:

config/torchlight.php

1<?php
2 
3return [
4 'theme' => 'material-theme-palenight',
5 'theme' => 'nord',
6 
7 // Your API token from torchlight.dev.
8 'token' => env('TORCHLIGHT_TOKEN'),
9 
10 // If you want to register the blade directives, set this to true.
11 'blade_directives' => true,
12];
Code highlighting powered by torchlight.dev.

Images on Laravel Vapor

This section only applies if you're hosting your blog on Laravel Vapor (which you should be!) When using Vapor, the path of your static assets changes on each deploy. Laravel gives us a nice asset() helper to solve for this, but when you're writing in markdown you don't have access to that.

Fortunately it's very easy to write a commonmark extension.

In my case, I have a commonmark extension that looks for images with relative paths, and then uses the asset helper to update them to the right path.

VaporAssetWrapping.php

1<?php
2class VaporAssetWrapping implements ExtensionInterface
3{
4 public function register(ConfigurableEnvironmentInterface $environment)
5 {
6 $environment->addEventListener(DocumentParsedEvent::class, [$this, 'onDocumentParsed']);
7 }
8 
9 public function onDocumentParsed(DocumentParsedEvent $event)
10 {
11 $walker = $event->getDocument()->walker();
12 
13 while ($event = $walker->next()) {
14 $node = $event->getNode();
15 
16 if (!$node instanceof Image || !$event->isEntering()) {
17 continue;
18 }
19 
20 if (Str::startsWith($node->getUrl(), '/')) {
21 $node->setUrl(asset($node->getUrl()));
22 }
23 }
24 }
25}

Again, you can just add that to your markdown.php and now all your assets will work on Vapor.

config/markdown.php

1'extensions' => [
2 // Torchlight syntax highlighting
3 TorchlightExtension::class,
4 
5 // The location of our static assets varies based on wherever
6 // Vapor puts them. This will point them to the right spot.
7 VaporAssetWrapping::class,
8 
9 // Add `#` and links to headers.
10 HeadingPermalinkExtension::class,
11 
12 // Add attributes straight from markdown.
13 AttributesExtension::class
14],

Extra Attributes

The last commonmark extension I use is one that lets me add attributes straight from markdown. It's another 1st party commonmark extension called attributes. It just lets you sprinkle HTML attributes right into your markdown files.

For example, whenever I write

1markdown.php {.filename}

it will render it as

1<span class="filename">markdown.php</span>

That's exactly how I add those filename tags to all my code samples, as well as sprinkling in Tailwind CSS classes where necessary.

Image Previews

The final thing that I do to make my blog polished and complete is generate social images based on the content of the blog. I use a service called Placid that lets me generate them on-the-fly instead of having to make a social card for each post.

Here's what the one for this post looks like.

Social media sharing card

This image is auto-generated from the title of the post based on a template I defined at Placid.

If you share this post on Twitter (which you should!) then this is the image that will pop up.

Markdone

I hope you've gotten a thing or two from this post, and I hope you feel empowered to roll your own, barebones blog! It's a lot of fun to work with vanilla Laravel and have everything exactly like you want it!

Thanks for reading! My name is Aaron and I'm currently working at small property tax firm in Texas called Resolute Property Tax Solutions, where I serve in dual roles as COO & CTO.

I work on a lot of projects. I'm building a shedquarters. I currently do a podcast, and I used to do a different podcast.

If you ever have any questions or want to chat, I'm always on Twitter
Copyright 2013 - 2021, Aaron Francis.