Monday, May 16, 2022

Laravel Tutorial: How to Fetch Website Favicons

 On this laravel tutorial, we gonna create a favicon fetcher. This is our simple and straightforward solution to fetch the favicon from a website. We will be using Favicon Fetcher, an opensource library from here.

Before you start, you'll need to make sure that you've got an application running at least PHP 8.0 and Laravel 8.

You can install the package via Composer:

composer require ashallendesign/favicon-fetcher

You can then publish the package's config file using the following command:

php artisan vendor:publish --provider="AshAllenDesign\FaviconFetcher\FaviconFetcherProvider"

The package should now be installed and ready to use. You should also have a new config/favicon-fetcher.php config file.

Favicon Fetch method

To fetch a favicon from a website, you can use the fetch method which will return an instance of AshAllenDesign\FaviconFetcher\Favicon:

use AshAllenDesign\FaviconFetcher\Facades\Favicon;
 
$favicon = Favicon::fetch('https://apps.unnes.ac.id');

Storing Favicon

You can store a favicon using your default filesystem disk like so:

use AshAllenDesign\FaviconFetcher\Facades\Favicon;
 
$faviconPath = Favicon::fetch('https://apps.unnes.ac.id')->store('favicons');
 
// $faviconPath is now equal to: "/favicons/abc-123.ico"

Caching Favicon

If you have a page displaying 100 websites and their favicons, we would need to find the favicon's URL on each page load. So you need a caching mechanism. You can use this library.

use AshAllenDesign\FaviconFetcher\Facades\Favicon;
 
$faviconPath = Favicon::fetch('https://apps.unnes.ac.id')
    ->cache(now()->addDay());

0 comments:

Post a Comment