master_template/app/Http/Controllers/RolesController.php
2024-06-23 17:02:56 +05:45

104 lines
3.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Repositories\PermissionRepository;
use Illuminate\Http\Request;
use App\Models\Roles;
use Illuminate\Http\RedirectResponse;
use Brian2694\Toastr\Facades\Toastr;
use App\Repositories\RoleRepository;
use Log;
use Exception;
class RolesController extends Controller
{
private $roleRepository;
private $permissionRepository;
public function __construct(
RoleRepository $roleRepository,
PermissionRepository $permissionRepository
) {
$this->roleRepository = $roleRepository;
$this->permissionRepository = $permissionRepository;
}
public function index(Request $request)
{
$data['title'] = "List Roles";
createActivityLog(RolesController::class, 'index', ' Roles index');
$roles = $this->roleRepository->findAll();
return view("crud.generated.roles.index", compact('roles'));
}
public function create()
{
$data['title'] = "Create Role";
$data['editable'] = false;
$data['permissionLists'] = $this->permissionRepository->getPermissionListsArrangedByPrefix();
return view('crud.generated.roles.create', $data);
}
public function store(Request $request): RedirectResponse
{
try {
$validatedData = $request->validate([
'name' => 'required',
'guard_name' => 'string',
]);
$role = $this->roleRepository->create($validatedData);
$role->permissions()->attach($request->permissions);
Toastr::success('New Role has been created', 'Title', ["positionClass" => "toast-top-center"]);
} catch (\Throwable $th) {
Toastr::success('Error while creating', 'Title', ["positionClass" => "toast-top-center"]);
}
return redirect()->route('roles.index');
}
public function show(string $id)
{
//
}
public function edit($id)
{
$data['title'] = "Edit Role";
$data['editable'] = false;
$data['role'] = $this->roleRepository->getRoleById($id);
$data['permissionIDsArray'] = $data['role']?->permissions?->pluck('id')->toArray();
$data['permissionLists'] = $this->permissionRepository->getPermissionListsArrangedByPrefix();
return view('crud.generated.roles.edit', $data);
}
public function update(Request $request, $id): RedirectResponse
{
try {
$validatedData = $request->validate([
'name' => 'required',
'guard_name' => 'string',
]);
$role = $this->roleRepository->update($id, $validatedData);
$role->permissions()->sync($request->permissions);
Toastr::success('Role has been updated', 'Title', ["positionClass" => "toast-top-center"]);
} catch (\Throwable $th) {
Toastr::success('Error while updating', 'Title', ["positionClass" => "toast-top-center"]);
}
return redirect()->route('roles.index');
}
public function destroy($id)
{
$this->roleRepository->delete($id);
Toastr::success('Role has been deleted', 'Title', ["positionClass" => "toast-top-center"]);
return response()->json(['status' => true, 'message' => 'Role has been deleted!']);
}
}