T
T
Tampik2016-01-06 18:23:28
Laravel
Tampik, 2016-01-06 18:23:28

How to login with login and email in Laravel 5.2?

Hello! How to log in both by login and by email, depending on what the user enters? Logging into laravel 5.2 by default via email, can be done by login by adding to AuthController.php
protected $username = 'login';
But then email is not included.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-01-06
@Tampik

First, when validating, make the username field required, and in Latin. I think it's logical.
Next, add a function to AuthController:

public function postLogin(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);
        $login = $request->input($this->loginUsername());
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email':'username';

        $request->merge([$field => $login]);
        $credentials = $request->only($field, 'password');

        if (Auth::attempt($credentials, $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($this->loginPath())
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }

UPD: Made a more up-to-date and correct version thanks to JhaoDa 's answer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question