Laravel Breeze Login with email or username

 

Installation Process:


       1. Laravel 

   I hope you have already installed the Laravel project and Breeze-Auth.       let's start the next step...

After completing the Install Process

    1. Step: Edit User Table File
        Path:                 project_dir\database\migrations\2014_10_12_000000_create_users_table.php

        
  public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username', 255);
            $table->string('name', 255);
            $table->string('email')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    
    2. Step: Edit Login Page:
        Note: Only Email Address Section Edit.

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



                                                
                                                            Fig: Login Page

    
    3. Step: Edit LoginRequest File
        Path: project_dir\app\Http\Requests\Auth\LoginRequest.php

     Editable Function Name: 
rules() , authenticate()  New Added Function Name: prepareForValidation() New Variable Added: $loginType

<?php

namespace App\Http\Requests\Auth;

use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class LoginRequest extends FormRequest
{
    
    protected $loginType;
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        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.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();

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

            throw ValidationException::withMessages([
                $this->loginType => trans('auth.failed'),
            ]);
        }

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

    /**
     * Ensure the login request is not rate limited.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function ensureIsNotRateLimited(): void
    {
        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.
     */
    public function throttleKey(): string
    {
        return Str::transliterate(Str::lower($this->input('email')).'|'.$this->ip());
    }

    protected function prepareForValidation()
    {
        $this->loginType = filter_var($this->input('login_type'),
        FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        $this->merge( [$this->loginType => $this->input('login_type')] );
    }
}




I hope you write the codes correctly. Then it will work. thank you.

Comments

Popular posts from this blog