fix redirect back roles

This commit is contained in:
arifal
2025-03-12 20:30:16 +07:00
parent b0d4d4c23b
commit 7a82ad5302
9 changed files with 56 additions and 55 deletions

View File

@@ -19,35 +19,22 @@ class RolesController extends Controller
*/ */
public function index(Request $request) public function index(Request $request)
{ {
$menuId = $request->query('menu_id'); $menuId = $request->query('menu_id') ?? $request->input('menu_id');
$user = Auth::user(); $permissions = $this->permissions[$menuId]?? []; // Avoid undefined index error
$userId = $user->id; $creator = $permissions['allow_create'] ?? 0;
$updater = $permissions['allow_update'] ?? 0;
$destroyer = $permissions['allow_destroy'] ?? 0;
// Ambil role_id yang dimiliki user return view("roles.index", compact('creator', 'updater', 'destroyer', 'menuId'));
$roleIds = DB::table('user_role')
->where('user_id', $userId)
->pluck('role_id');
// Ambil data akses berdasarkan role_id dan menu_id
$roleAccess = DB::table('role_menu')
->whereIn('role_id', $roleIds)
->where('menu_id', $menuId)
->first();
// Pastikan roleAccess tidak null sebelum mengakses properti
$creator = $roleAccess->allow_create ?? 0;
$updater = $roleAccess->allow_update ?? 0;
$destroyer = $roleAccess->allow_destroy ?? 0;
return view("roles.index", compact('creator', 'updater', 'destroyer'));
} }
/** /**
* Show the form for creating a new resource. * Show the form for creating a new resource.
*/ */
public function create() public function create(Request $request)
{ {
return view("roles.create"); $menuId = $request->query('menu_id');
return view("roles.create", compact('menuId'));
} }
/** /**
@@ -80,10 +67,11 @@ class RolesController extends Controller
/** /**
* Show the form for editing the specified resource. * Show the form for editing the specified resource.
*/ */
public function edit(string $id) public function edit(string $id, Request $request)
{ {
$menuId = $request->query('menu_id');
$role = Role::findOrFail($id); $role = Role::findOrFail($id);
return view("roles.edit", compact('role')); return view("roles.edit", compact('role', 'menuId'));
} }
/** /**
@@ -121,12 +109,13 @@ class RolesController extends Controller
} }
} }
public function menu_permission(string $role_id){ public function menu_permission(string $role_id, Request $request){
try{ try{
$menuId = $request->query('menu_id');
$role = Role::findOrFail($role_id); $role = Role::findOrFail($role_id);
$menus = Menu::all(); $menus = Menu::all();
$role_menus = RoleMenu::where('role_id', $role_id)->get() ?? collect(); $role_menus = RoleMenu::where('role_id', $role_id)->get() ?? collect();
return view('roles.role_menu', compact('role', 'menus', 'role_menus')); return view('roles.role_menu', compact('role', 'menus', 'role_menus', 'menuId'));
}catch(\Exception $e){ }catch(\Exception $e){
return redirect()->back()->with("error", $e->getMessage()); return redirect()->back()->with("error", $e->getMessage());
} }
@@ -134,8 +123,9 @@ class RolesController extends Controller
public function update_menu_permission(Request $request, string $role_id){ public function update_menu_permission(Request $request, string $role_id){
try{ try{
$menuId = $request->query('menu_id');
$validateData = $request->validate([ $validateData = $request->validate([
"permissions" => "array", "permissions" => "nullable|array",
"permissions.*.allow_show" => "nullable|boolean", "permissions.*.allow_show" => "nullable|boolean",
"permissions.*.allow_create" => "nullable|boolean", "permissions.*.allow_create" => "nullable|boolean",
"permissions.*.allow_update" => "nullable|boolean", "permissions.*.allow_update" => "nullable|boolean",
@@ -144,6 +134,13 @@ class RolesController extends Controller
$role = Role::find($role_id); $role = Role::find($role_id);
// Jika `permissions` tidak ada atau kosong, hapus semua permissions terkait
if (!isset($validateData['permissions']) || empty($validateData['permissions'])) {
$role->menus()->detach();
return redirect()->route("roles.index", ['menu_id' => $menuId])
->with('success', 'All menu permissions have been removed.');
}
$permissionsArray = []; $permissionsArray = [];
foreach ($validateData['permissions'] as $menu_id => $permission) { foreach ($validateData['permissions'] as $menu_id => $permission) {
$permissionsArray[$menu_id] = [ $permissionsArray[$menu_id] = [
@@ -158,7 +155,7 @@ class RolesController extends Controller
// Sync will update existing records and insert new ones // Sync will update existing records and insert new ones
$role->menus()->sync($permissionsArray); $role->menus()->sync($permissionsArray);
return redirect()->route("role-menu.permission", $role_id)->with('success','Menu Permission updated successfully'); return redirect()->route("roles.index", ['menu_id' => $menuId])->with('success','Menu Permission updated successfully');
}catch(\Exception $e){ }catch(\Exception $e){
Log::error("Error updating role_menu:", ["error" => $e->getMessage()]); Log::error("Error updating role_menu:", ["error" => $e->getMessage()]);
return redirect()->route("role-menu.permission", $role_id)->with("error", $e->getMessage()); return redirect()->route("role-menu.permission", $role_id)->with("error", $e->getMessage());

View File

@@ -6,6 +6,7 @@ class CreateRoles {
initCreateRole() { initCreateRole() {
const toastNotification = document.getElementById("toastNotification"); const toastNotification = document.getElementById("toastNotification");
const toast = new bootstrap.Toast(toastNotification); const toast = new bootstrap.Toast(toastNotification);
let menuId = document.getElementById("menuId").value;
document document
.getElementById("btnCreateRole") .getElementById("btnCreateRole")
.addEventListener("click", async function () { .addEventListener("click", async function () {
@@ -41,7 +42,7 @@ class CreateRoles {
result.message; result.message;
toast.show(); toast.show();
setTimeout(() => { setTimeout(() => {
window.location.href = "/roles"; window.location.href = `/roles?menu_id=${menuId}`;
}, 2000); }, 2000);
} else { } else {
let error = await response.json(); let error = await response.json();

View File

@@ -31,6 +31,7 @@ class Roles {
tableContainer.innerHTML = ""; tableContainer.innerHTML = "";
let canUpdate = tableContainer.getAttribute("data-updater") === "1"; let canUpdate = tableContainer.getAttribute("data-updater") === "1";
let canDelete = tableContainer.getAttribute("data-destroyer") === "1"; let canDelete = tableContainer.getAttribute("data-destroyer") === "1";
let menuId = tableContainer.getAttribute("data-menuId");
// Create a new Grid.js instance only if it doesn't exist // Create a new Grid.js instance only if it doesn't exist
this.table = new gridjs.Grid({ this.table = new gridjs.Grid({
columns: [ columns: [
@@ -38,38 +39,38 @@ class Roles {
"Name", "Name",
"Description", "Description",
{ {
name: "Action", name: "Action",
formatter: (cell) => { formatter: (cell) => {
let buttons = `<div class="d-flex justify-content-center gap-2">`; let buttons = `<div class="d-flex justify-content-center gap-2">`;
if (canUpdate) { if (canUpdate) {
buttons += ` buttons += `
<a href="/roles/${cell}/edit" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center"> <a href="/roles/${cell}/edit?menu_id=${menuId}" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center">
<i class='bx bx-edit'></i> <i class='bx bx-edit'></i>
</a> </a>
<a href="/roles/role-menu/${cell}" class="btn btn-primary btn-sm d-inline-flex align-items-center justify-content-center"> <a href="/roles/role-menu/${cell}?menu_id=${menuId}" class="btn btn-primary btn-sm d-inline-flex align-items-center justify-content-center">
Role Menu Role Menu
</a> </a>
`; `;
} }
if (canDelete) { if (canDelete) {
buttons += ` buttons += `
<button data-id="${cell}" class="btn btn-sm btn-red btn-delete-role d-inline-flex align-items-center justify-content-center"> <button data-id="${cell}" class="btn btn-sm btn-red btn-delete-role d-inline-flex align-items-center justify-content-center">
<i class='bx bxs-trash'></i> <i class='bx bxs-trash'></i>
</button> </button>
`; `;
} }
if (!canUpdate && !canDelete) { if (!canUpdate && !canDelete) {
buttons += `<span class="text-muted">No Privilege</span>`; buttons += `<span class="text-muted">No Privilege</span>`;
} }
buttons += `</div>`; buttons += `</div>`;
return gridjs.html(buttons); return gridjs.html(buttons);
},
}, },
},
], ],
pagination: { pagination: {
limit: 50, limit: 50,

View File

@@ -6,6 +6,7 @@ class UpdateRoles {
initUpdateRole() { initUpdateRole() {
const toastNotification = document.getElementById("toastNotification"); const toastNotification = document.getElementById("toastNotification");
const toast = new bootstrap.Toast(toastNotification); const toast = new bootstrap.Toast(toastNotification);
let menuId = document.getElementById("menuId").value;
document document
.getElementById("btnUpdateRole") .getElementById("btnUpdateRole")
.addEventListener("click", async function () { .addEventListener("click", async function () {
@@ -41,7 +42,7 @@ class UpdateRoles {
result.message; result.message;
toast.show(); toast.show();
setTimeout(() => { setTimeout(() => {
window.location.href = "/roles"; window.location.href = `/roles?menu_id=${menuId}`;
}, 2000); }, 2000);
} else { } else {
let error = await response.json(); let error = await response.json();

View File

@@ -9,7 +9,6 @@
@include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Menu']) @include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Menu'])
<x-toast-notification /> <x-toast-notification />
<x-modal-confirmation buttonText="Delete" confirmationMessage="Are you sure you want to delete this?" />
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">

View File

@@ -5,11 +5,12 @@
@include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role']) @include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role'])
<x-toast-notification /> <x-toast-notification />
<input type="hidden" id="menuId" value="{{ $menuId ?? 0 }}">
<div class="row d-flex justify-content-center"> <div class="row d-flex justify-content-center">
<div class="col-md-6"> <div class="col-md-6">
<div class="card"> <div class="card">
<div class="card-header d-flex justify-content-end"> <div class="card-header d-flex justify-content-end">
<a href="{{ route('roles.index') }}" class="btn btn-sm btn-secondary">Back</a> <a href="{{ route('roles.index', ['menu_id' => $menuId]) }}" class="btn btn-sm btn-secondary">Back</a>
</div> </div>
<div class="card-body"> <div class="card-body">
<form action="{{route("api.roles.store")}}" method="post" id="formCreateRole" data-redirect="{{route("roles.index")}}"> <form action="{{route("api.roles.store")}}" method="post" id="formCreateRole" data-redirect="{{route("roles.index")}}">

View File

@@ -5,11 +5,12 @@
@include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role']) @include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role'])
<x-toast-notification/> <x-toast-notification/>
<input type="hidden" id="menuId" value="{{ $menuId ?? 0 }}">
<div class="row d-flex justify-content-center"> <div class="row d-flex justify-content-center">
<div class="col-md-6"> <div class="col-md-6">
<div class="card"> <div class="card">
<div class="card-header d-flex justify-content-end"> <div class="card-header d-flex justify-content-end">
<a href="{{ route('roles.index') }}" class="btn btn-sm btn-secondary">Back</a> <a href="{{ route('roles.index', ['menu_id' => $menuId]) }}" class="btn btn-sm btn-secondary">Back</a>
</div> </div>
<div class="card-body"> <div class="card-body">
<form id="formUpdateRole" action="{{route("api.roles.update", $role->id)}}" method="post" > <form id="formUpdateRole" action="{{route("api.roles.update", $role->id)}}" method="post" >

View File

@@ -9,7 +9,6 @@
@include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role']) @include('layouts.partials/page-title', ['title' => 'Settings', 'subtitle' => 'Role'])
<x-toast-notification/> <x-toast-notification/>
<x-modal-confirmation buttonText="Delete" confirmationMessage="Are you sure you want to delete this?" />
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
@@ -17,12 +16,13 @@
<div class="card-body"> <div class="card-body">
<div class="d-flex flex-wrap justify-content-end align-items-center mb-2"> <div class="d-flex flex-wrap justify-content-end align-items-center mb-2">
@if ($creator) @if ($creator)
<a href="{{ route('roles.create')}}" class="btn btn-success btn-sm d-block d-sm-inline w-auto">Create</a> <a href="{{ route('roles.create', ['menu_id' => $menuId])}}" class="btn btn-success btn-sm d-block d-sm-inline w-auto">Create</a>
@endif @endif
</div> </div>
<div id="table-roles" <div id="table-roles"
data-updater="{{ $updater }}" data-updater="{{ $updater }}"
data-destroyer="{{ $destroyer }}"> data-destroyer="{{ $destroyer }}"
data-menuId="{{ $menuId }}">
</div> </div>
</div> </div>
</div> </div>

View File

@@ -8,11 +8,11 @@
<div class="col-md-12"> <div class="col-md-12">
<div class="card"> <div class="card">
<div class="card-header d-flex justify-content-end"> <div class="card-header d-flex justify-content-end">
<a href="{{ route('roles.index') }}" class="btn btn-sm btn-secondary">Back</a> <a href="{{ route('roles.index', ['menu_id' => $menuId]) }}" class="btn btn-sm btn-secondary">Back</a>
</div> </div>
<div class="card-body"> <div class="card-body">
<h5>Manage Permissions for Role: {{ $role->name }}</h5> <h5>Manage Permissions for Role: {{ $role->name }}</h5>
<form action="{{route("role-menu.permission.update", $role->id)}}" method="post"> <form action="{{ route('role-menu.permission.update', ['role_id' => $role->id]) }}?menu_id={{ $menuId }}" method="post">
@csrf @csrf
@method("put") @method("put")
<table class="table"> <table class="table">