Skip to content

laravie/authen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Oct 15, 2023
5d4f87b Β· Oct 15, 2023
Oct 15, 2023
Jul 13, 2023
Oct 15, 2023
Oct 15, 2023
Oct 15, 2023
Aug 1, 2021
Apr 14, 2021
Dec 28, 2019
Dec 28, 2019
Nov 23, 2016
Jan 6, 2022
Oct 15, 2023
Apr 15, 2023
Aug 1, 2021
Dec 18, 2022
Oct 15, 2023

Repository files navigation

User Authentication Identifiers for Laravel

tests Latest Stable Version Total Downloads Latest Unstable Version License Coverage Status

Imagine you need to login a user with either "email", "username" or "phone number" just like how Facebook allows it. This is not possible with Laravel since you're limited to only one unique username/identifier key. This package attempt to solve the issue by allowing to use a unified key "identifier" and you can customize which attributes Laravel should check during authentication.

Installation

To install through composer, run the following command from terminal:

composer require "laravie/authen"

Usages

Service Provider

First you can attach the auth provider on App\Providers\AuthServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravie\Authen\BootAuthenProvider;

class AuthServiceProvider extends ServiceProvider
{
    use BootAuthenProvider;

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        $this->bootAuthenProvider();
    }
}

User Model

Secondly, you need to update the related App\User (or the eloquent model mapped for auth).

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravie\Authen\AuthenUser;

class User extends Authenticatable
{
    use Notifiable, AuthenUser;

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return array<int, string>
     */
    public function getAuthIdentifiersName()
    {
        return ['email', 'username', 'phone_number'];
    }
}

With this setup, you can now check either email, username or phone_number during authentication.

Configuration

Lastly, you need to update the config config/auth.php:

<?php

return [

    // ...

    'providers' => [
        'users' => [
            'driver' => 'authen',
            'model'  => App\User::class,
        ],
    ],

    // ...
];

Examples

Here's an example how to login.

<?php 

use Illuminate\Support\Facades\Auth;
use Laravie\Authen\Authen;

$data = [Authen::getIdentifierName() => '[email protected]', 'password' => 'foobar'];

if (Auth::attempt($data)) {
    // you can logged in, you can also pass your phone number of username to `identifier`.
}