Posts Learn Components Snippets Categories Tags About
/

How to Self Host Google Fonts Locally in Laravel

Learn how to self-host Google Fonts locally in your Laravel application to ensure no latency and fonts are always available.

Created on Aug 15, 2021

36 views

To easily self-host google fonts in Laravel, you can make use of a package from "spatie" called "laravel-google-fonts". This package is very straightforward to use and below are the steps to integrate it with your Laravel project.

Step 1: Install Using Composer
You can install this package by using composer by running the command below.
composer require spatie/laravel-google-fonts

Step 2: Publish Configuration
Once it's installed you can publish the package configuration file. The configuration file will be used to specify the fonts that you want to include / self-host.
php artisan vendor:publish --provider="Spatie\GoogleFonts\GoogleFontsServiceProvider" --tag="google-fonts-config"

Step 3: Define The Google Fonts
You can define the google fonts that you want to self-host within the array value like below. Do note that the other configs are omitted for the sake of this example.
<?php // config/google-fonts.php

return [
    'fonts' => [
        'default' => 'https://fonts.googleapis.com/css2?family=Inter:ital,[email protected],400;0,700;1,400;1,700&display=swap',
        'code' => 'https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,[email protected],400;0,700;1,400&display=swap',
        'roboto' => 'https://fonts.googleapis.com/css2?family=Roboto:[email protected];400;500;700;900'
    ],
    /* other configs */
];

Step 4: Refer from Blade File
Now that you have defined that, you can refer to the font from your blade file using the "@googlefonts" directive. By default, it will get the "default" font and for those that have a different name, you can specify it by passing a param to the directive like below.
@googlefonts
@googlefonts('roboto') // get the google font

For the full code example, it will be as follows.
{{-- resources/views/layouts/app.blade.php --}}
<html>
<head>
    {{-- Loads Inter Font --}}
    @googlefonts

    {{-- Loads Roboto Font --}}
    @googlefonts('code')
</head>
<body></body>
</html>

Extra: Prefetch Fonts
You might want to prefetch the fonts in the production by running the prefetch command.
php artisan google-fonts:fetch

Do note that you will need to have the storage linked for this if you are using the "public" driver. If you have not yet link it then run the command below.
php artisan storage:link

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More