使用名称或用户名Laravel 5.2进行身份验证

时间:2016-07-24 21:31:00

标签: php laravel authentication laravel-5 laravel-5.2

是一个Laravel初学者。所以我希望用户能够使用姓名或电子邮件登录。 身份验证是通过php artisan make:auth生成的。 使用Laravel 5.2

- 编辑 -  我应该把它放在哪里?

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法。

 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.',
            ]);
        }

或者你可以使用多次尝试:

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
}

答案 1 :(得分:0)

这是我们在Laravel 5.2中进行电子邮件或用户名验证的方法,看一下我AuthController的类似案例的代码

namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectTo = '/';
    protected $username = 'username';
    protected $maxLoginAttempts = 10;
    protected $redirectPath = '/';
    protected $redirectAfterLogout = '/';

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

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:syscare_users',
            'password' => 'required|confirmed|min:6',
            'username' => 'max:255|min:6|alpha_num|unique:syscare_users',
        ]);
    }


    /**
     * Handle a login request to the application.  - Overriding
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (Auth::attempt(['username' => $request->username , 'password' => $request->password], $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }
        elseif(Auth::attempt(['email' => $request->username , 'password' => $request->password],$request->has('remember')))
        {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }


        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return redirect()->back()
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }

    /**
     * Get the failed login message. - Override
     *
     * @return string
     */

     protected function getFailedLoginMessage()
        {
            return Lang::has('auth.failed')
                ? Lang::get('auth.failed')
                : 'Invalid username/email or password.';
        }

}