Gravatars are immensely popular in the online world, as is Laravel for PHP based web applications these days. We can easily use Gravatars within our Laravel based applications with my SimpleGravatar package. Letting your users use one on your site has many advantages – the least being user experience. If a user has a Gravatar set up and it’s linked to their site account the instant they join, they don’t have to go to the bother of adding a site specific avatar for themselves. Similarly, if the user doesn’t have an avatar set up at all, Gravatar can provide a default image to use.
Setting up our users table
When we create our users table in Laravel (likely via a Migration – if you’re not using one, you’re doing it wrong), we’ll want to be sure to add an avatar field. This can be a simple string type field with a default value.
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function($table)
{
...
$table->string('avatar')->default('gravatar');
...
});
}
...
}
This will mean that when a new user registers, the avatar field for their record will default to “gravatar” if they do not set a custom on-site avatar image.
Installing the package
Installing the SimpleGravatar package is extremely easy via Composer. Simply add the following line to your Laravel project’s compsoer.json file under the “require” section:
"euantor/simple-gravatar": "dev-master"
Now all we need to do is add the Service Provider to our project’s app/config/app.php file as part of the ‘providers’ array key:
'providers' => array( ... 'Euantor\SimpleGravatar\SimpleGravatarServiceProvider', ...
Adapting our User model to utilize Gravatars
Now all we have to do is adapt our User model to utilize the Gravatar if the user does not have a custom one set. To do this, we must add a new accessor method to the class:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface
{
...
public function getAvatarAttribute($val)
{
if (empty($val) OR $val == 'gravatar') {
$gravatar = App::make('simplegravatar');
return $gravatar->setDefault('mm')->getGravatar($this->attributes['email']);
}
return $val;
}
...
}
What the above code does is check if the ‘avatar’ field is empty for the user being fetched or if it equals the string “gravatar”. If it’s either, it returns the URL to the user’s Gravatar image (or the Mystery Man default image if the user has no avatar associated to their email).
Enhancements
You may wish to implement a few enhancements to this method if using it on a live site. It’s not particularly optimal to be making remote calls to the service for all user images – what if the external server goes down for whatever reason? It might be a good idea to implement a cache type mechanism whereby user’s avatars are fetched and stored locally for a certain amount of time (or stored on a CDN). This is entirely up to you though.


