I am currently working on a system where people can submit a registration request. The admin will need to accept the request in order for the user to be able to sign in. In my database, I have a field called is_request
and with every registration this field is set by default to 1 (is set by default to 1 in the database) , meaning yes. When a user with this field set to 1, tries to log in, they will need to be notified that their account has not yet been activated. How can I accomplish this?
When the user tries to register the following happens:
protected function create(array $data) { $users = User::where('role_id', 1)->get(); $user = User::create([ 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'email' => $data['email'], 'role_id' => 3, 'activated' => 0, 'user_token' => Str::random(32), 'password' => Hash::make($data['password']), ]); foreach($users as $admin) { $admin->notify(new registerRequest($user)); } Mail::to($user->email)->send(new RegisterRequestSend($user)); return $user; }
And when the admin in the backend “accepts” the request the field is_request
will be set to 0 and the user needs to be able to sign into the app.
The login controller looks like this
class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = RouteServiceProvider::HOME; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } }
Advertisement
Answer
You could create an global middleware that checks if the user is accepted or not:
namespace AppHttpMiddleware; use Closure; class CheckIfAccepted { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { if (auth()->check() && !auth()->user()->isAccepted) { auth()->logout(); return redirect('not-accepted'); } return $next($request); } }
This middleware will log out any authed user that aren’t accepted and redirect them to a route of your choice.
Change auth()->user()->isAccepted
to an attribute or method that contains information about the accepted-status.
If you want the middleware to run at every request, you can add it as a global middleware by adding it the the $middleware
-array in app/Http/Kernel.php
.
You can read more about middleware and how to create them in the docs: https://laravel.com/docs/master/middleware