Skip to content
Advertisement

Laravel – Multiple User Logins Under One Main User Account

My application has the structure of monthly subscriptions that give you a single “admin” account login responsible for billing. Under that main user account, there can be numerous employees, some, but not all, with their own logins with limited permissions.

What is the best way to structure this?

I have done the following:

User Table excerpt: id | employe_id | name | email | password | etc…

Employee Table excerpt: id | user_id | first_name | last_name | etc…

Indexes:

Schema::table('employees', function($t) {
    $t->foreign('user_id')
        ->references('id')
        ->on('users')
        ->onUpdate('cascade')
        ->onDelete('cascade');
});

Schema::table('users', function($t) {
    $t->foreign('employee_id')
    ->references('id')
    ->on('employees')
    ->onUpdate('cascade')
    ->onDelete('cascade');
});

But this raises a couple issues:

  1. When an employee logs in, he should be seeing records tagged with the main user account’s id, but when using Auth::id, the employee’s user id is returned.

  2. At times, the employee’s user id is needed to tag certain records as theirs, but also the main user accounts id needs to be recorded with the record.

Using Sentry or a Permissions/Roles based system solves a few issues, but doesn’t solve the issue of being able to have Auth return both employee id and main user account id.

Is there a better way of doing this than the approach I am taking? Is there some easy solution I’m missing?

(This is my first question on StackOverflow, so still learning how this works.)

Advertisement

Answer

I ended up adding a “user_type” column to the users table. With that, I create the following method in my Users model:

public function rootId()
{
    if (Auth::user()->user_type == Config::get('settings.employee'))
    {
        return Auth::user()->employee->user_id;
    }
    else if (Auth::user()->user_type == Config::get('settings.admin'))
    {
        return Auth::user()->id;
    }
}

This appears to be a working solution for my situation.

If any have a better solution, or see issues with mine, please let me know.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement