Raphael
Raphael

Reputation: 107

Laravel 7 Authentication Check user status in other tables

I have three tables:

users

id
name
email
password
status

companies

id
name
status

users_companies

id
users_id
companies_id
default
status

At the time of logging in, I want to verify that the status of all the tables where the user refers, is equal to 1.

is there a way to join the tables when logging in?

how could I issue a custom message if any of the tables has the status of 0. and not only show: these credentials do not match our records.

Upvotes: 0

Views: 1308

Answers (2)

bdtiger
bdtiger

Reputation: 521

Assume your model name for companies table is Company and model name for users_companies table is UserCompany.

You have to override credentials and authenticated methods in LoginController

First, check users status is true

protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['status'] = true;
    return $credentials;
}

After that, check UserCompany and Company status is true. If any of them is not true then logout and redirect to the login page showing an error message.

protected function authenticated(Request $request, $user)
{
    $userCompany = UserCompany::where('users_id', $user->id)->first();
    $company = Company::find($userCompany->companies_id);
    if (!$userCompany->status || !$company->status) {
        $this->logout($request);
        return $this->sendFailedLoginResponse($request);
    }
}

Upvotes: 3

djunehor
djunehor

Reputation: 961

Assuming you have a LoginController that uses AuthenticatesUser trait, create this method in your LoginController to override the default:

 /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
    }

Do your extra logic in the method

Upvotes: 1

Related Questions