Support the ongoing development of Laravel.io →
posted 10 years ago
Database
Last updated 2 years ago.
0

Why would you need two primary keys in your users table? You could just keep the incrementing id field by itself, unless 'user_id' is something custom unique identifier generated by your app? <-- first thought...

To access (easily) you could change the 'assigned_roles' field 'user_id' to a foreign key referencing your 'users' table. Like so:

$table->foreign('user_id')->references('id')->on('users');

Then, to retrieve the roles relative to the user, in your users table model you can have something like this (if your user can have many roles).

    public function roles()
    {
        return $this->hasMany('<Whatever your model is called for your assigned_roles table>');
    }

Lastly, to retrieve a certain user's roles (assuming you are using Auth for authentication), you could use something like this:

$rolesUserHas = UserModel::find(Auth::user()->id)->roles;

If not using Auth, then provide the user id manually or in any other way you see fit.

Let me know if this helps.

Last updated 2 years ago.
0

Thanks Ayyobro, It works.

Sometimes, we must make sure the custom primary key (not using id) must not null to be able create the foreign key.

Last updated 2 years ago.
0

No problem, happy to help.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

dashracer dashracer Joined 2 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.