Autentikasi Username atau Email pakai Laravel 9 Breeze

Memakai Laravel 9 dan Breeze sebagai autentikasi dan untuk masuk / login memakai Username atau pun Email Untuk instalasi breeze ada di sini enter image description here

Buka file /app/Http/Requests/Auth/LoginRequest.php ganti kode pada LoginRequest class :

 use IlluminateValidationValidationException;

class LoginRequest extends FormRequest
 {

 protected $login_by;
 protected $login;

 protected function prepareForValidation(){
  $this->login_by = filter_var($this->input('login_by'),FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
  $this->login = $this->input('login_by');
  $this->merge([ $this->login_by  => $this->login ]);
 }
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
  */
 public function authorize()
     {
         return true;
     }

     /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
     public function rules()
{
    return [
        'email' => ['required_without:username','string','email','exists:users,email'],
        'username' => ['required_without:email','string','exists:users,username'],
        'password' => ['required', 'string'],
    ];
}

/**
 * Attempt to authenticate the request's credentials.
 *
 * @return void
 *
 * @throws IlluminateValidationValidationException
 */
public function authenticate()
{
    $this->ensureIsNotRateLimited();

    if (! Auth::attempt($this->only($this->login_by, 'password'), $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());

        throw ValidationException::withMessages([
            'login_by' => trans('auth.failed'),
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}

/**
 * Ensure the login request is not rate limited.
 *
 * @return void
 *
 * @throws IlluminateValidationValidationException
 */
public function ensureIsNotRateLimited()
{
    if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
        return;
    }

    event(new Lockout($this));

    $seconds = RateLimiter::availableIn($this->throttleKey());

    throw ValidationException::withMessages([
        'email' => trans('auth.throttle', [
            'seconds' => $seconds,
            'minutes' => ceil($seconds / 60),
        ]),
    ]);
}

/**
 * Get the rate limiting throttle key for the request.
 *
 * @return string
 */
public function throttleKey()
     {
         return Str::transliterate(Str::lower($this->input('email')).'|'.$this->ip());
     }
 }

Buka File: resources/views/auth/login.blade.php update field email ganti dengan kode ini:

 <div class="mt-4">
 <x-input-label for="login_by" :value="__('Username / Email')" />
 <x-text-input id="login_by" class="block mt-1 w-full" type="text" name="login_by" :value="old('login_by')" required autofocus />
 <x-input-error :messages="$errors->get('login_by')" class="mt-2" />
 </div>

Related posts

Published by

kris

kris

Admin dan kontributor utama untuk website ini