How to create an automated sitemap generator in Laravel
Udgivet 2018-06-20 - Skrevet af Philip Sørensen
You don't need any fancy tools to create a sitemap for your website, you can get Laravel to do it for you and it's even easy. All it requires is one package, and a simple function. I'll use my cocktail website, Mixologisten
, as an example for the sitemap.
To generate the sitemap automatically, we'll be using the laravel-sitemap
package. It can be installed with a simple composer install command, like shown below, and a publish command.
With the package installed, it is time to use it. I created a controller with one function, the function that creates the sitemap and saves it to a file. The entire controller can be seen below.
The first few lines initializes the sitemap and sets up a cache for it (it is off by default). It is also possible to set the duration of the cache (in minutes) in the setCache
-function, like so: $sitemap->setCache('laravel.sitemap', 60)
Thereafter I check whether or not the sitemap is already cached, because if it is I just need to show it. However, if the sitemap isn't cached I need to create it. This is done by adding all of the URLs one by one. They are added with the add
-function which takes 4 variables: URL, date, priority, and frequency of change.
The first page added is the frontpage which is hardcoded in. The remainder of pages however are either saved as a page or as a cocktail in the database, which means I can automatically run through all of the remaining URLs. For the date I use date('c')
which is a ISO 8601 timestamp that includes timezone.
Finally, after running through all the URLs, the sitemap is stored as a XML-file in the root of the website, and then I redirected to the file. In my case, the XML-file is used to keep Google Webmaster posted with changes on the website.
Der er ingen kommentarer.