I'm new to Laravel, and this is aimed at newcomers too. Long-timers feel free to tell me why this is bad practice, as I genuinely don't know any better yet.
As at 24th August 2019 - using Laravel 5.8 - This is my personal implementation.
Assumptions made:
- You started out using Artisan Make:Auth
- You've added 'active' as a bool (tinyInt) to your User table and updated the relevant Models etc...
- You're trying to prevent users from gaining access to your application via standard Auth, when: 'active' = 0.
If this is the case, you can leave your LoginController alone.
Instead open "Illuminate/Auth/Middleware/Authenticate.php" and replace the handle() method with:
public function handle($request, Closure $next, ...$guards) { if(!$request->user()->active){ // either abort with simple 403 access denied page // abort(403, "You don't have permissions to access this area"); // OR force Logout and redirect back to the login page return redirect('login')->with($this->auth->logout()); } $this->authenticate($request, $guards); return $next($request); }
Note: Auth::logout() won't work here, but it's already pulled in via the constructor at the top of the file.
public function __construct(Auth $auth) { $this->auth = $auth; }
So you can just use $this->auth->logout(); instead.
Thinking about it - You could very easily swap 'Active' for pretty much any criteria and update this middleware the very same way! Hope this helps!