Search code examples
laravelmulti-user

Multi user type design in Laravel


I'm a bit puzzled on how to best create an architecture for a multiple user type account. Watching the Laracasts episode on users and roles I figured a single User model with a Role model would be a good approach. However, rethinking the data I need for my different type of users varies, as for some users I need full address data and for others a name would be enough (to gently great them upon login). However, a Vistor might turn into a Customer. In fact, even the MerchantEmployee could become a Customer. This makes me wondering what my database design would become, e.g.

users => UserModel <fields> email, password
role: visitor => VistorModel <fields> name
role: customer => CustomerModel <fields> name, street, zipcode, ...
role: merchantowner => MerchantOwnerModel <fields> name, street, zipcode, ...
role: merchantemployee => MerchantEmployeeModel <fields> name

Would then all the Vistor, Customer, MerchantOwner and MerchantEmployee models have a user_id-column? Or how would you design such functionality?


Solution

  • I think to create two tables

    First one is users

    +----------+---------+-------+
    |   Col    |  Type   | Notes |
    +----------+---------+-------+
    | id       | bigInt   | PK/AI |
    | name     | VARCHAR | NN    |
    | email    | VARCHAR | NN|UN |
    | password | VARCHAR | NN    |
    | role     | ENUM    | NN    |
    +----------+---------+-------+
    

    The second one is user_data

    +----------------------+---------+-------+
    |         Col          |  Type   | Notes |
    +----------------------+---------+-------+
    | id                   | bigInt  | PK/AI |
    | user_id              | bigInt  | FK    |
    | address              | VARCHAR | NN    |
    | {WHAT EVER YOU WANT) |         |       |
    +----------------------+---------+-------+
    

    And the relation to be one to one.

    I recommend to use Laravel validation "required_if" to valid data before process it to database.

    $this->validation($request, [
     'address' => 'required_if:role,merchant_owner'
    ]);