Storing User Roles in Session Laravel

1.4k Views Asked by At

Hello there I am working on a project in Laravel in which i need to assign permission to each user so that i could verify on each blade file or controller function to check whether the current user has the permission to perform this. Moreover, the side nav links are also generated using these permissions dynamically. I created two tables:

1: User => [ID, Name .....]
2: Permissions => [ID, Name, user_id(fk)]

To solve this problem, i have stored all the permissions of users in session at the time of login. So that i can verify all permissions on each page and generate links fetching from session.

Is that good approach or there is any better solution for this

3

There are 3 best solutions below

0
On

It would be good if you had share more code but i can see what you are want to archive. Firstly you dont need to store in the Session because you have already a relation between user Object and Permission. Add to your User model this lines of code:

public function permissions() {
    return $this->belongsTo(User::class);
}

Then you have access in your blade or controller to the permission. Small example in the controller:


$user = User::find(1);
dd($user->permissions);

// you can write a condition to check if user has Permission etc.
0
On

Yes you can store this is the session. But the more better option will be to get the permission through relation object like

user::find(1)->permissions()
0
On

Well if you're asking "better solution" ... but I Not sure if it's too late for this information since you're already developing the project. However, I would recommnend this package for your long term management (for both user and dev).

Spatie Laravel-permission package

It has Role based permission and Direct permission design (which is similar to your design). Once you installed the package then role and permission tables are created for you.

Once you created desired roles with permissions, it's easy for you to manage which page to allow for which role and which button show be shown.

You can check roles in your controller for those who can view this page. In blade, you can check both roles and permission for which button to show or disable.

Hence, your don't need to worry about session settings or session expires. It's better for maintaining and development in future.

The Spatie package has simple syntax and easy to work with.

Installation:

 composer require spatie/laravel-permission

Syntax:

Basic usage and syntax

There are plenty information or tutorials out there.