Using Laravel with Netlify
Are you looking for a way to host your Laravel site statically on Netlify using the tools you're already comfortable with?
Well, look no further. Thanks to the amazing team of Spatie this is now very much a thing – with minimal setup you'll be up and running in no time using one of their latest packages called Laravel Export.
Let me show you how.
Let's assume we have a fresh installation of Laravel including a few basic routes, initialized and pushed our codebase to a GitHub repository and connected the repository with Netlify.
Get the party started by adding
spatie/laravel-export to your project via composer:
# @ path/to/your/project $ composer require spatie/laravel-export # Optionally publish the config file $ php artisan vendor:publish
Next, let's generate the static bundle of our site using the export command to make sure everything is working as expected, you should see something like this:
$ php artisan export Starting export... Files were saved to disk `export`
By default, Laravel Export will save the static bundle in a
dist/ folder in your application root. More in-depth information regarding the configuration is available in the documentation.
Before we push our changes to git, let's add our entire site bundle to
.gitignore and generate the static files on the server instead using a
netlify.toml file placed in our application root:
# .gitignore dist/
# netlify.toml [build] command = "php artisan export" publish = "dist/" [build.environment] PHP_VERSION = "7.2"
☝🏻Make sure you use the same publish path as you've configured in Laravel Export, in this case it's
dist/ as we didn't make any configuration changes.
Okay, easy. Right? Lastly, we need to configure some
.env variables before we build and publish our site. Let's head over to the Netlify dashboard:
Go to Site settings > Build & deploy > Build environment variables > Edit variables, add the following and hit save:
APP_DEBUG=true APP_ENV=production APP_KEY=YOUR_LARAVEL_APP_KEY APP_NAME=Your site name APP_URL=https://yoursite.com/
Voila! You're done 🎉. Now trigger a new deploy within Netlify and go visit your site url. How cool is that, eh?
As described in the documentation, it's important to link pages within your app properly in order for them to be included in the export. You can specify an array of URL's that will be recursively crawled and exported to HTML if needed.
🔥 Hawt tip
Going with this approach for your static site, I would highly recommend adding the
spatie/sheets package for some extra flavor. This enables you to store and retrieve content (such as pages, blog posts etc) using markdown and front matter. Awesome!
One of the major benefits of this is that we now have our entire site in version control, eliminating the need for a database entirely.