Last active
November 6, 2017 09:03
-
-
Save DmmitryIs/a2bcef0009c0fed292f0dc96cf9b0d86 to your computer and use it in GitHub Desktop.
Laravel 5.4/5.5 auth by email or username
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Auth; | |
use App\Http\Controllers\Controller; | |
use Illuminate\Foundation\Auth\AuthenticatesUsers; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Auth; | |
class LoginController extends Controller | |
{ | |
/* | |
|-------------------------------------------------------------------------- | |
| Login Controller | |
|-------------------------------------------------------------------------- | |
| | |
| This controller handles authenticating users for the application and | |
| redirecting them to your home screen. The controller uses a trait | |
| to conveniently provide its functionality to your applications. | |
| | |
*/ | |
use AuthenticatesUsers; | |
/** | |
* Where to redirect users after login. | |
* | |
* @var string | |
*/ | |
protected $redirectTo = '/'; | |
/** | |
* Create a new controller instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
$this->middleware('guest')->except('logout'); | |
} | |
// Changes for login by username (or email, by default) | |
public function attemptLogin(Request $request) | |
{ | |
$isEmail = filter_var($request->{$this->username()}, FILTER_VALIDATE_EMAIL); | |
$loginField = $isEmail ? $this->username() : 'name'; // name - is username field in your db | |
return Auth::attempt( | |
[$loginField => $request->{$this->username()}, 'password' => $request->password], | |
$request->has('remember') | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment