L
L
LNK2018-09-24 20:27:14
Laravel
LNK, 2018-09-24 20:27:14

How to store additional model data in Laravel?

Greetings. I use RBAC approach based on laravel + laratrust framework . The role can be issued to different user models. For each role, I have a type (just a number) that determines which models the role can apply to. For example, the "User Role" role type can only be issued to App\User models. Question in the following: I need to store some additional information on roles. Moreover, the structure of this information depends on the type of role. For example, in roles with the "User role" type, I need to store the "is_super_user" field, and in roles with the "Chat Role" type, I need to store a completely different set of fields. How can this be done correctly?
Considered these options:
- just make the data field of the role, which stores all the information in json. Simple, but not very beautiful, it will not be possible to make any selections, searches for additional. information, etc.
- make a dynamic connection hasOne. That is something like this:

public function data()
{
    switch ($this->role_type) {
        case 1: return $this->hasOne('App\UserRoleDataModel');
        case 2: return $this->hasOne('App\ChatRoleDataModel');
    }
}

The disadvantages of the approach are that you need to have a bunch more models just to store additional information about the role. Well, in general, it looks a bit strange ..
What can you advise on this situation? I will be glad to hear your suggestions.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
float64, 2018-10-14
@float64

Laravel has a special plugin for storing metadata: https://github.com/jarektkaczyk/eloquence/wiki/Metable
I use it, it works fine.
Shortcomings found empirically:
1) all metadata values ​​will be stored as string
2) be careful with Boolean variables in metadata. If you store false in the meta property then $model->hasMeta('somefield') will also return false.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question