Thursday, 1 May 2025

DAY11 ปรับ Login

01 Nov 2024
60

หลังจากที่เราได้ทำการปรับ permission ให้เข้าไปตาม role ของตัวเองแล้ว เราก็จะมาปรับในส่วนของ login กันบ้างเพื่อให้ login โดยใช้ username หรือ phone ได้ ดังนั้นเรามาเริ่มปรับกันเลย โดยที่เริ่มจากปรับ form login หน้าแรกกันก่อนที่ resource>views>auth>login.blade.php

edit views login

edit views login

 

       <div>
            <x-input-label for=”login” :value=”__(‘Email/Name/Phone’)” />
            <x-text-input id=”login” class=”block mt-1 w-full” type=”text” name=”login” :value=”old(‘login’)” required autofocus autocomplete=”username” />
        </div>
edit-login-views

edit-login-views

 

จากนั้นเราก็มาแก้ LoginRequest.php ที่ app>http>Auth

เพิ่ม

use App\Models\User;
use Illuminate\Support\Facades\Hash;
จากนั้นมาแก้ function rules
public function rules(): array
    {
        return [
            ‘login’ => [‘required’, ‘string’],
            ‘password’ => [‘required’, ‘string’],
        ];
    }
แก้ function authen
public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();
        $user =User::where(’email’,$this->login)
                    ->orWhere(‘name’,$this->login)
                    ->orWhere(‘phone’,$this->login)
                    ->first();
        if (!$user || !Hash::check($this->password,$user->password))
        {
            RateLimiter::hit($this->throttleKey());
           /* if (! Auth::attempt($this->only(’email’, ‘password’), $this->boolean(‘remember’))) {
                RateLimiter::hit($this->throttleKey()); */
            throw ValidationException::withMessages([
                ‘login’ => trans(‘auth.failed’),
            ]);
        }
        Auth::login($user,$this->boolean(‘remember’));
        RateLimiter::clear($this->throttleKey());
    }
จากนั้นก็ save แล้ว ทดสอบด้วยการเข้าด้วย เบอร์โทร หรือ username ดู  !เย้วันนี้คุณสำเร็จไปอีก 1 บทแล้ว