Recently at work I was upgrading Sentry to the newly open sourced Sentinel project by Cartalyst to take advantage of some of the features such as multiple persistences and multiple login attributes. I couldn’t find clear documentation to achieve multiple login attributes with Sentinel and Laravel so I decided to post here what I’ve found.
Sentinel by default has functionality for email/password logins in Laravel. If you’re like me and would like to be able to login in with email or username, here is what I’ve had to do.
First, we will have to create our own User class extending
vendor/cartalyst/sentinel/src/Users/EloquentUser.php
Your new Eloquent model would look something like the following:
use Cartalyst\Sentinel\Users\EloquentUser as SentinelUser;
class User extends SentinelUser {
protected $fillable = [
'email',
'username',
'password',
'last_name',
'first_name',
'permissions',
];
protected $loginNames = ['email', 'username'];
}
The ‘username’ attribute has been added to the model’s $fillable
attribute. Any extra attributes on your customized user model should be added to this array so that the model still works with Sentinel’s methods such as Sentinel::register()
. The $loginNames
attribute tells Sentinel which database columns can be used as a login field.
Next, publish Sentinel’s config to your application and then modify the configuration to point to your custom User model. Instructions on setup are here for Laravel 4 and Laravel 5.
'users' => [
'model' => 'Namespace\User',
],
When multiple login attributes are in use, authentication can be achieved by passing in the special array key 'login'
to the method Sentinel::authenticate()
. You can pass any fields from $loginNames
to the array key 'login'
.
Sentinel::authenticate([
'login' => 'fake@email.com',
'password' => 'password',
]);
That should give you a basic user using Sentinel that can login with username or email!