Auth Login: how to check more than just email/password?

Notice. Article updated in February 2018 for latest Laravel 5.6 version.
Laravel default authentication is awesome. But by default it works by checking two fields - email and password. What if we have some additional fields to check? For example, if user is approved? Let's say that in our users table we have a field approved with value 0 or 1. How to add that to login function? First things first - authentication happens in file app/Http/Controllers/Auth/LoginController.php. If you look at its code, you won't actually see any login function, but it uses a trait:
use AuthenticatesUsers;
That trait is loading some functions into the class and it's a part of Illuminate\Foundation so we cannot easily change that trait. But what we can do is override its functions in our class and make any changes we want. So we're interested in that trait's function credentials(), which looks like this:
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }
As I said before, we can just copy-paste that function into our LoginController.php (we have to also add use Illuminate\Http\Request; at the top of file) and make the changes we want, including adding more fields into authentication. In this case, we need to change function to this:
    public function credentials(Request $request)
    {
        $credentials = $request->only($this->username(), 'password');
        $credentials = array_add($credentials, 'approved', '1');
        return $credentials;
    }
As a result, logging in will happen with this SQL query:
select * from `users` where `email` = [your_email] and `approved` = 1 limit 1

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like