dhrubanka's avatar

Laravel 7.x login using phone instead of email with custom login that uses attemptLogin() method

I have been using a custom authentication system using the attemptLogin() in my loginController. Now, I want to login using phone instead of email. I have tried overriding the username() method in the Controller that returns the column field for the phone. However, using that with attemptLogin() doesn't seem to work. My loginController is given below

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\User;
use Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

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

    public function showLoginForm()
    {
        // Get URLs
        $urlPrevious = url()->previous();
        $urlBase = url()->to('/');

        // Set the previous url that we came from to redirect to after successful login but only if is internal
        if(($urlPrevious != $urlBase . '/login') && (substr($urlPrevious, 0, strlen($urlBase)) === $urlBase)) {
            session()->put('url.intended', $urlPrevious);
        }

        return view('auth.login');
    }
    public function username()
    {
        return 'PHONE';
    }

    protected function attemptLogin(Request $request)
    {

        $user = User::where('PHONE', $request->phone)
                    ->where('PASSWORD', $request->password)
                    ->first();
        //dd($user);

        if(!isset($user)){
            return false;
        }

        return    Auth::login($user);
    }

}

PS- I have disabled password hashing for a particular use case

0 likes
2 replies
Sinnbeck's avatar

Here you check if you have set the variable $user. And you always have as it is set in the line before

if(!isset($user)){

//change it to 
if(!$user){
jlrdw's avatar

This should be no different than using username instead of email. You should be fine with just plain out of the box Authentication.

Please or to participate in this conversation.