TheGamerDev TheGamerDev - 2 months ago 21x
PHP Question

Auth with either the name or username Laravel 5.2

Am a Laravel Beginnner. So i want the user the be able to login with either the name or email.
The auth is generated via

php artisan make:auth
Am using Laravel 5.2

-- EDIT --
And where should i put this ?


You can use following approach.

 public function login(LoginRequest $request)
            $field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';//Validating if user has entered email or username
            $request->merge([$field => $request->input('login')]);//Use selected field to generate input array 

            if ($this->auth->attempt($request->only($field, 'password')))//authenticate
                return redirect('/');

            return redirect('/login')->withErrors([
                'error' => 'These credentials do not match our records.',

Or you can use multiple tries:

if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {

        echo "success with username!";

elseif (Auth::attempt(['email'=> $request->username, 'password' => $request->password])) {

        //redirect or do something

else {
      //redirect or do something