Home / Snippets / How to Self Host Google Fonts Locally in Laravel
How to Self Host Google Fonts Locally in Laravel cover

How to Self Host Google Fonts Locally in Laravel

2K

3 years ago

0 comments

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,wght@0,400;0,700;1,400;1,700&display=swap',
        'code' => 'https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,700;1,400&display=swap',
        'roboto' => 'https://fonts.googleapis.com/css2?family=Roboto:wght@300;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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this