Get 2024 Templates Mega Bundle!14 Bootstrap, Vue & React Templates + 3 Vector Sets
Get for 99$

Roles & Permission


Hi devs,

I am using Starterkit Metronic Laravel 10.0, i want to implement roles and permission in my project structure in a sense that:
1. user has his dashboard, and pages related to his account only
2. Manager has his dashboard and view all users activities
3. Support has access to some of the features of manager
4. admin with full privileges

show me how i can use the default roles & permission to achieve this.

Regards


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(

Replies (5)


Hi,

Starterkit Metronic Laravel uses the Laravel Permissions plugin from Spatie for role and permission management, you can follow the documentation of the Laravel Permissions package for detailed instructions on how to implement roles and permissions. You also have to customize the application based on your requirements.

Start by defining the roles you mentioned - user, manager, support, and admin. You can do this in your database or using roles crud in the demo.

Assign roles to users based on their role in the system.

Use middleware or gates provided by Laravel to restrict access to certain pages or features based on the user's role.

Customize the dashboard for each role. You can create separate dashboard views for user, manager, support, and admin, and display them based on the user's role.

Define permissions for each role.

Use Laravel's authorization features like `@can` directive in Blade templates or `Gate::allows` in your controllers to check if a user has permission to perform a certain action.

Here's a basic example of how you might define roles and permissions in Laravel:


// Define roles
$roles = [
"user" => ["user_dashboard"],
"manager" => ["manager_dashboard", "view_users"],
"support" => ["support_dashboard"],
"admin" => ["admin_dashboard", "full_privileges"],
];

// Assign roles to users
$user->assignRole("user");
$manager->assignRole("manager");
$support->assignRole("support");
$admin->assignRole("admin");

// Restrict access using middleware
Route::middleware("role:manager")->group(function () {
Route::get("/manager-dashboard", "ManagerController@dashboard");
Route::get("/view-users", "ManagerController@viewUsers");
});

// Check permissions in Blade templates
@can("view_users")
<a href="/view-users" target="_blank">View Users</a>
@endcan

// Check permissions in controllers
if (Gate::allows("full_privileges")) {
// Perform action
}


Please note that this is a basic example and you may need to customize it based on your specific requirements.

Thanks



Hello Faizal,

I implement it , now i want the system to check the users when Login and redirect them to their respective dashboards, and regular users that register by themselves using the register page with no roles/permission should be redirected to the /client/dashboard.

i tried the following middleware but not working:


Route::middleware("role:Administrator")->group(function () {
Route::get('/admin/dashboard', [DashboardController::class, 'index'])->name('admin_dashboard');

});
Route::middleware("role:Manager")->group(function () {
Route::get('/manager/dashboard', [DashboardController::class, 'manager'])->name('manager_dashboard');

});

Route::middleware("role:Support")->group(function () {
Route::get('/manager/dashboard', [DashboardController::class, 'support'])->name('support_dashboard');

});

Route::get('/client/dashboard', [DashboardController::class, 'client'])->name('dashboard');


kindly show me how to configure the check on the Login page.

Thanks



Hi

Here is a general guide to implement roles and permissions and redirect users to their respective dashboards upon login:

Use the Spatie Laravel Permission package to define roles and permissions. You can create roles like ‘Administrator’, ‘Manager’, ‘Support’, and ‘User’, and assign permissions to these roles as needed.

When a user registers, assign them a default role. For regular users, you might assign the ‘User’ role.

Your middleware setup seems correct, but ensure that you have registered your custom middleware in app/Http/Kernel.php.

Override the authenticated method in your LoginController to check the user’s role and redirect them accordingly. Here’s an example:

protected function authenticated(Request $request, $user)
{
if ($user->hasRole("Administrator")) {
return redirect("/admin/dashboard");
} elseif ($user->hasRole("Manager")) {
return redirect("/manager/dashboard");
} elseif ($user->hasRole("Support")) {
return redirect("/support/dashboard");
} elseif ($user->hasRole("User")) {
return redirect("/client/dashboard");
}

return redirect("/"); // Default redirection for any other cases
}


For users who register themselves, you can set a default role in the create method of your RegisterController. For example:

protected function create(array $data)
{
$user = User::create([
// ... other user data
]);

$user->assignRole("User"); // Assign default role
return $user;
}


Ensure your routes are protected with the appropriate middleware to prevent unauthorized access.

You may refer to this docs:
https://medium.com/@miladev95/step-by-step-guide-to-user-role-and-permission-tutorial-in-laravel-10-1fecdabfdea0



Hi Faizal,

I made the following changes and it's switching between the dashboards, but i notice the page doesn't reload after authenticated, i had to manually refresh the page then it will refirect me to the respective dashboard:

login.blade
I REMOVED the: data-kt-redirect-url="{{ route('dashboard') }}"

and made the following changes:

app/http/controllers/Auth/AuthenticatedSessionController:
public function store(LoginRequest $request)
{
$request->authenticate();

$request->session()->regenerate();

// $user = Auth::user();
// $role = $user->roles->first()->name;

$user = Auth::user();

if ($user->roles->isEmpty()) {
// Handle users without roles (e.g., redirect them to a default dashboard)
return redirect()->route('dashboard');
}

// Log::info('User role: ' . $role);
$role = $user->roles->first()->name;

if ($user && $user->hasRole('Administrator')) {
return redirect()->route('admin.dashboard');
} elseif ($user && $user->hasRole('Manager')) {
return redirect()->route('manager.dashboard');
} elseif ($user && $user->hasRole('Store')) {
return redirect()->route('store.dashboard');
}else {
return redirect()->route('dashboard');
}
}

app/http/middleware/RedirectIfAuthenticated:
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;

foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
$user = Auth::user();

if ($user->roles->isEmpty()) {
// Handle users without roles (e.g., redirect them to a default dashboard)
return redirect()->route('dashboard');
}

$role = $user->roles->first()->name;

// Log::info('Authenticated user: ' . $user->id);
// Log::info('User role: ' . $role);

if ($role === 'administrator') {
return redirect()->route('admin.dashboard');
} elseif ($role === 'manager') {
return redirect()->route('manager.dashboard');
} elseif ($role === 'support') {
return redirect()->route('support.dashboard');
}else {
return redirect()->route('dashboard');
}
}
}

return $next($request);
}

public/assets/js/custom/authentication/sign-in/general.js:

Swal.fire({
text: "You have successfully logged in!",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
}).then(function () {
// Reload the page
window.location.reload();
});
} else{



assist me with a way to resolve this issue of refreshing the page after authenticated the Logged in user.
Thanks



Hi

Your AuthenticatedSessionController and RedirectIfAuthenticated middleware seem to handle the redirection based on the user's role correctly. Ensure that these redirections are working as expected.

Verify that the authentication process is working correctly. Ensure that the authenticate() method in your controller successfully authenticates the user and that the regenerate() method regenerates the session.


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(
Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(