How to Load Gravatar Image in Laravel

Today, I’m going to let you know how to load the gravatar image in Laravel. We’re going to use creativeorange/gravatar package.

Table of Contents

  1. Install Package
  2. Use in Controller
  3. Use in Blade File
  4. Configuration

Install Package

Run this artisan command to install the package:

composer require creativeorange/gravatar

For Laravel 5.3 or below, we need to add this service provider and aliase in config/app.php file:

app.php
'providers' => [
	//....
	'Creativeorange\Gravatar\GravatarServiceProvider::class',
],
'aliases' => [
	//....
	'Gravatar' => 'Creativeorange\Gravatar\Facades\Gravatar::class',
],

Finally, publish the config by running the php artisan vendor:publish command.

Use in Controller

We can easily get gravatar image using this package. Here’re some examples:

// import
use Creativeorange\Gravatar\Facades\Gravatar;

// get image
Gravatar::get('[email protected]');

// set fallback image
 Gravatar::fallback('http://example.com/avatar.jpg')->get('[email protected]');

Use in Blade File

Here’s the example to use in blade (view) file:

<img src="{{ Gravatar::get('[email protected]') }}">

Configuration

We’re able to define some sizes & options in the package’s config file. The config file is located at config/gravatar.php. Here’s an example of config:

return [
    'default' => [
        'size'   => 80,
        'fallback' => 'mm',
        'secure' => false,
        'maximumRating' => 'g',
        'forceDefault' => false,
        'forceExtension' => 'jpg',
    ],
    'small-secure' => [
        'size'   => 30,
        'secure' => true,
    ],
    'medium' => [
        'size'   => 150,
    ]
];

Then we use the following syntax:

Gravatar::get('[email protected]', 'small-secure');
Gravatar::get('[email protected]', 'medium');
Gravatar::get('[email protected]', 'default');
Gravatar::get('[email protected]'); // will use the default group

We can also pass config like:

Gravatar::get('[email protected]', ['size'=>200]);

That’s all. Thank you.