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
php artisan storage:link
Leave a reply