Login menggunakan username atau email di laravel

Secara bawaa, Laravel Auth menggunakan email untuk login, dalam artikel ini kita tambahkan fungsi untuk login menggunakan username atau email. Apabila belum membuat fungsi login dengan Laravel Auth, bisa melihat artikel pada halaman berikut ini https://dudu.web.id/2020/02/generate-laravel-authentication-di-laravel-versi-6/

Buat migration untuk menambahkan kolom username

php artisan make:migration add_username_to_users_table

Ubah isinya menjadi seperti berikut

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddUsernameToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('username')->after('name'); 
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('username');
        });
    }
}

Jalankan migration dengan php artisan migrate

Ubah model User.php dengan menambahkan username pada atribut fillable

protected $fillable = [
        'name','username', 'email', 'password',
    ];

Pada RegisterController.php tambahkan username pada array di fungsi validator dan create

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

Tambahkan input username pada register.blade.php

<div class="form-group row">
    <label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>

    <div class="col-md-6">
        <input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" >

        @error('username')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

Coba register dengan field yang sudah ditambahkan username

Ubah halaman login.blade.php dengan mengganti atribut email menjadi ‘login’ dan tambahkan perintah untuk menampilkan error username disamping error email

<input type="text" class="form-control {{ $errors->has('username') || $errors->has('email') ?'is-invalid':'' }}" name="login" value="{{ old('username') ? old('username') : old('email')  }}"
        placeholder="Username or Email" />
    @if ($errors->has('username') || $errors->has('email'))
    <span class="invalid-feedback">
        <strong>{{ $errors->first('username') ? $errors->first('username') : $errors->first('email')  }}</strong>
    </span>
    @endif

Ubah pada LoginController.php dengan menambahkan atribut username serta menambahkan fungsi findUsername dan username

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;
    protected $username;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        $this->username = $this->findUsername();
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function findUsername()
    {
        $login = request()->input('login');

        $fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        request()->merge([$fieldType => $login]);

        return $fieldType;
    }

    /**
     * Get username property.
     *
     * @return string
     */
    public function username()
    {
        return $this->username;
    }
}

Selesai, sekarang kita bisa login menggunakan email atau username yang telah di register sebelumnya.

Semoga bermanfaat