Elegant method of generating Gravatar avatar address by Laravel

  • 2021-08-31 07:25:27
  • OfStack

Preface

Gravatar avatar has become a very popular universal avatar in blogs and forums. Gravatar avatar is supported in messages or login registration, whether it is Wordpress, Z-Blog, Typecho, Emlog, etc. Laravel Gravatar expansion package provides the simplest and most elegant way to generate Gravatar globally recognized avatar address. Flexible and convenient API, supporting multi-connection configuration and mirrored address.

Project home page: https://github.com/ElfSundae/laravel-gravatar

Installation


$ composer require elfsundae/laravel-gravatar

Configure

Although this expansion pack can be used without any setup, it is recommended to use a configuration file to configure the Gravatar connection (connection) in order not to hard-code parameters such as picture size in the code and to use the mirror address (you know).

For performance, this expansion pack does not register service provider, so you need to manually copy the configuration file to your application:


$ cp vendor/elfsundae/laravel-gravatar/config/gravatar.php config/gravatar.php

The configuration file has very detailed comments, please read it yourself.

In the configuration file, you can configure multiple Gravatar connections (connection) for your application. In addition to the image parameters of Gravatar (see https://en. gravatar. com/site/implement/images/), you can also set the url mirror address. The default name of connection is default.

Configuration example:


'default' => [
 'url' => 'https://gravatar.cat.net/avatar',
 'size' => 120,
],
'small' => [
 'url' => 'https://gravatar.cat.net/avatar',
 'size' => 40,
],
'large' => [
 'url' => 'https://gravatar.cat.net/avatar',
 'size' => 460,
],

API

There is only one global helper function: gravatar ()


/**
 * Generate Gravatar avatar URL for the given email address.
 *
 * @param string $email Email or email hash
 * @param string|int $connection Connection name or image size
 * @param string|int $size Connection name or image size
 * @return string
 */
function gravatar($email, $connection = 'default', $size = null)

Use sample


//  For  email  Generate an avatar address, using the  "default"  Connection configuration 
gravatar('foo@example.com');
//  For  email  Adj.  MD5  Hash value to generate avatar address, using  "default"  Connection configuration 
gravatar('b48def645758b95537d4424c84d1a9ff');
//  Use  "large"  Connection configuration 
gravatar($email, 'large');
//  Use  "default"  Connection configuration and override  size  Parameter is  100
gravatar($email, 100);
//  Use  "avatar"  Connection configuration and override  size  Parameter is  100
gravatar($email, 'avatar', 100);
//  Or: 
gravatar($email, 100, 'avatar');

Summarize


Related articles: