I am new to Laravel but fell in love with the framework and decided to use it for my project.
I have a field active
and by default I've set it to 0
. In the Attempt()
method, I've set $credentials['active'] = 1
. When I logout and login again, this works fine.
But when I register a user, it automatically logs the user in without checking active field.
In registersUsers.php replace the line:
With the following:
This worked for me, I use Laravel 5.2
I assume you are using the
AuthenticatesAndRegistersUsers
trait in your controller.The registration is carried by the
postRegister()
method in that trait, which calls thelogin()
method after creating a new user.You can override this method in your controller and call the
login()
method only when theactive
field istrue
. So, yourpostRegister()
method will be something like:I would avoid adding the
active
field to the credentials - this is an authorisation issue rather than an authentication one.For this, I'd use a middleware to check if a logged-in user is active or inactive. In 5.3, the middleware would look like this:
This middleware then has to be registered inside
Kernel.php
:And then finally we protect all our routes with it:
The advantage of this approach of course is that we can display a more relevant error message than the general 'These credentials do not match our records' that people with bad auth details get. So the user would know it's not their fault they can't log in.
Anyway, with the approach in the accepted answer, ensure you have done the same for when the user successfully resets their password as they are also auto-logged in then.