No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UserController.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. namespace App\Http\Controllers\Admin\User_management;
  3. use App\Helpers\Helper;
  4. use App\Http\Controllers\Controller;
  5. use Hashids;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\DB;
  8. use Validator;
  9. use Illuminate\Support\Facades\Route;
  10. //load modelmu
  11. use App\User;
  12. use Illuminate\Support\Facades\Hash;
  13. use Spatie\Permission\Models\Role;
  14. use App\Model\Master\MasterUdd;
  15. use App\Model\ModelHasRoles;
  16. use Yajra\Datatables\Datatables;
  17. use Auth;
  18. class UserController extends Controller
  19. {
  20. /**
  21. * Untuk CRUD Biar cepat
  22. * Silahkan ganti
  23. * User:: => dengan model anda
  24. * $user_id => ganti dengan id di model anda
  25. */
  26. /**
  27. * Title untuk judul di web
  28. * route digunakan untuk tempat resource (file path) + routing (route/web) diusahain sama ya biar gak ngubah"
  29. */
  30. private $title = 'App User Management | User';
  31. /**jangan lupa diganti*/
  32. private $route = 'admin.user_management.user.'; //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
  33. private $namespace_controller = 'Admin\User_management';
  34. private $url_prefix = 'user-management/user/';
  35. public function __construct()
  36. {
  37. // DB::enableQueryLog();
  38. // $this->middleware('permission:user-list|user-create|user-update|user-delete', ['only' => ['index', 'create', 'update']]);
  39. // $this->middleware('permission:user-create', ['only' => ['create', 'create_action']]);
  40. // $this->middleware('permission:user-update', ['only' => ['update', 'update_action']]);
  41. // $this->middleware('permission:user-delete', ['only' => ['delete']]);
  42. }
  43. /**
  44. * Ini contoh crud yang sudah jalan
  45. * index digunakna untuk tampilan awal dari menu yang akan dibuat
  46. */
  47. public function index()
  48. {
  49. if (session('success')) {
  50. alert()->html('', session('success'), 'success');
  51. }
  52. if (session('error')) {
  53. alert()->html('', session('error'), 'error');
  54. }
  55. // if (empty(Helper::is_super_admin())) {
  56. // return redirect('logout');
  57. // }
  58. $data = [
  59. //bawaan
  60. 'title' => $this->title,
  61. 'route' => $this->route,
  62. 'data' => User::get(),
  63. ];
  64. // dd($data);
  65. return view($this->route . 'index', $data);
  66. }
  67. public function getData()
  68. {
  69. $query = User::join('model_has_roles as model_role', 'model_role.model_id', 'users.id')
  70. ->where('role_id', 1); //super admin
  71. return Datatables::of($query)
  72. ->addIndexColumn()
  73. ->addColumn('role_name', function ($query) {
  74. $role_name = $query->roles()->get()->pluck('name')->toArray();
  75. $jumlah_data = count($role_name);
  76. foreach ($role_name as $key => $value) {
  77. $semicolon = '';
  78. if (($key + 1) > $jumlah_data) {
  79. $semicolon = ',';
  80. }
  81. $name = $value . $semicolon;
  82. }
  83. return $name;
  84. })
  85. ->addColumn('aksi', function ($query) {
  86. /**cek role */
  87. $aksi = '';
  88. if (Auth::user()->can('user-update')) {
  89. $aksi .= "<a href='" . route($this->route . 'update', ['user_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Edit</a>";
  90. }
  91. if (Auth::user()->can('user-delete')) {
  92. // $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['user_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
  93. }
  94. return $aksi;
  95. })
  96. ->rawColumns(['aksi'])
  97. ->toJson();
  98. }
  99. /**
  100. * create digunakan untuk menampilkan tampilan buat
  101. */
  102. public function create()
  103. {
  104. /**set role dengan cara dibagi 4 - 4 */
  105. $data = [
  106. //bawaan
  107. 'title' => $this->title,
  108. 'route' => $this->route,
  109. ];
  110. if (session('success')) {
  111. alert()->html('', session('success'), 'success');
  112. }
  113. if (session('error')) {
  114. alert()->html('', session('error'), 'error');
  115. }
  116. return view($this->route . 'create', $data);
  117. }
  118. /**
  119. * create_action digunakan untuk aksi post
  120. * lengkap dengan validatornya
  121. */
  122. public function create_action(Request $request)
  123. {
  124. /**digunakan untuk set rule validator */
  125. $rules = [
  126. 'name' => 'required|min:4|unique:users,name',
  127. 'email' => 'required|unique:users,email',
  128. 'password' => 'required|min:6',
  129. ];
  130. /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
  131. $alert = [
  132. 'unique' => ':attribute sudah tersedia',
  133. 'required' => 'The :attribute harus diisi',
  134. 'min' => ':attribute minimal :min karakter'
  135. ];
  136. $validator = Validator::make($request->all(), $rules, $alert);
  137. if ($validator->passes()) {
  138. /**menggunakan transaction */
  139. DB::beginTransaction();
  140. $insert = [
  141. 'name' => $request['name'],
  142. 'password' => Hash::make($request['password']),
  143. 'email' => $request['email']
  144. ];
  145. $query = User::create($insert);
  146. $data_role['role_id'] = 1; //super admin
  147. $query->assignRole($data_role);
  148. if ($query) {
  149. DB::commit();
  150. $message = 'Berhasil';
  151. return redirect(route($this->route . 'index'))->with('success', Helper::parsing_alert($message));
  152. } else {
  153. DB::rollback();
  154. $message = 'Gagal';
  155. return redirect()->back()->with('error', Helper::parsing_alert($message));
  156. }
  157. }
  158. /**kenapa menggunakan back ? karena baliknya pasti ke halaman sebelumnya */
  159. $message = Helper::parsing_alert($validator->errors()->all());
  160. return redirect()->back()->with('error', $message)->withInput();
  161. }
  162. /** update sama seperti create hanya saja digunakan untuk update (viewnya saja) */
  163. public function update($user_id)
  164. {
  165. if (session('success')) {
  166. alert()->html('', session('success'), 'success');
  167. }
  168. if (session('error')) {
  169. alert()->html('', session('error'), 'error');
  170. }
  171. $user_id = Hashids::decode($user_id);
  172. $data_udd = MasterUdd::get();
  173. if (!empty($user_id)) {
  174. $role = Role::get();
  175. $jumlah_role = $role->count();
  176. $limit = 4;
  177. $take = 0;
  178. $jumlah_looping = ceil($jumlah_role / $limit);
  179. $arr_role = [];
  180. for ($i = 0; $i < $jumlah_looping; $i++) {
  181. // $cek_limit[] = $limit;
  182. // $cek_take[] = $take;
  183. $limit_data = 4;
  184. $role = Role::take($limit_data)->skip($take)->get();
  185. $cek_data[] = $role;
  186. $arr_role[$i] = $role;
  187. $take = $limit;
  188. $limit += 4;
  189. }
  190. $cek_data = User::where('id', $user_id[0])->first();
  191. $cek_data->role = $cek_data->roles->pluck('id')->toArray();
  192. $cek_data->udd_id = $cek_data->petugas->unit_donor_darah_id ?? null;
  193. if ($cek_data) {
  194. $data = [
  195. //bawaan
  196. 'title' => $this->title,
  197. 'route' => $this->route,
  198. 'data' => $cek_data,
  199. 'role' => $arr_role,
  200. 'udd' => $data_udd,
  201. ];
  202. return view($this->route . 'update', $data);
  203. }
  204. $message = 'Id tidak ditemukan atau sudah dihapus';
  205. return redirect()->back()->with('error', $message);
  206. }
  207. $message = 'Id tdak ditemukan';
  208. return redirect()->back()->with('error', $message);
  209. }
  210. /**update_action POST
  211. * Logikanya :
  212. * 1. Cek Hashids::decode dari role_id apalah benar" di hash ?
  213. * -iya
  214. * 2. Cek ID yang didapatkan dari hash apakah benar adanya ?
  215. * -iya
  216. * 3. proses validate
  217. * -iya
  218. * 4. Proses update
  219. * - iya benar
  220. * - tidak salah
  221. * - tidak return error
  222. * - tidak return Id tdak ditemukan
  223. * -tidak skip reutrn id null
  224. */
  225. public function update_action(Request $request)
  226. {
  227. /**digunakan untuk set rule validator */
  228. $rules = [
  229. 'name' => 'required|min:4',
  230. 'email' => 'required',
  231. ];
  232. /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
  233. $alert = [
  234. 'required' => 'The :attribute harus diisi',
  235. 'min' => ':attribute minimal :min karakter'
  236. ];
  237. $validator = Validator::make($request->all(), $rules, $alert);
  238. $user_id = Hashids::decode($request['id']);
  239. if (!empty($user_id)) {
  240. /**cek apakah id ada ? */
  241. $cek_data = User::where('id', $user_id[0])->first();
  242. if ($cek_data) {
  243. /**cek apakah id rolenya benar" ada di DB ? */
  244. if ($validator->passes()) {
  245. /**validatornya */
  246. $update = [
  247. 'name' => $request['name'],
  248. 'email' => $request['email'],
  249. ];
  250. /**jika passwordnya disii */
  251. if ($request['password']) {
  252. $update['password'] = Hash::make($request['password']);
  253. }
  254. DB::beginTransaction();
  255. ModelHasRoles::where('model_id', $user_id)->delete();
  256. $query = $cek_data->update($update);
  257. $role['role_id'] = 1;
  258. $cek_data->assignRole($role['role_id']);
  259. if ($query) {
  260. DB::commit();
  261. $message = 'Berhasil';
  262. return redirect(route($this->route . 'index'))->with('success', Helper::parsing_alert($message));
  263. } else {
  264. DB::rollback();
  265. $message = 'Gagal';
  266. return redirect()->back()->with('error', Helper::parsing_alert($message));
  267. }
  268. }
  269. $message = Helper::parsing_alert($validator->errors()->all());
  270. return redirect()->back()->with('error', $message);
  271. } else {
  272. $message = 'Id tdak ditemukan';
  273. return redirect()->back()->with('error', $message);
  274. }
  275. } else {
  276. $message = 'Id tidak boleh kosong';
  277. return redirect()->back()->with('error', $message);
  278. }
  279. }
  280. /**digunakan untuk delete
  281. * Logikanya :
  282. * 1. Cek hash id
  283. * -ya
  284. * 2. Cek id dari hash
  285. * - ya
  286. * 3. Proses delete
  287. * -Ya
  288. * -Tidak
  289. * - tidak return Id tidak ditemukan atau sudah dihapus
  290. * -tidak reutrn Id tdak ditemukan
  291. */
  292. public function delete_action($user_id)
  293. {
  294. $user_id = Hashids::decode($user_id);
  295. /**cek role idnya apakah ada ? */
  296. if (!empty($user_id)) {
  297. $cek_data = User::where('id', $user_id[0])->first();
  298. if ($cek_data) {
  299. DB::beginTransaction();
  300. $delete = $cek_data->delete();
  301. if ($delete) {
  302. DB::commit();
  303. $message = 'Succesfully';
  304. $response = [
  305. 'message' => $message,
  306. 'status' => true,
  307. ];
  308. return response()->json($response);
  309. } else {
  310. DB::rollback();
  311. $message = 'Gagal';
  312. $response = [
  313. 'message' => $message,
  314. 'status' => false,
  315. ];
  316. return response()->json($response);
  317. }
  318. }
  319. $message = 'Id tidak di temukan atau sudah di hapus';
  320. $response = [
  321. 'message' => $message,
  322. 'status' => false,
  323. ];
  324. return response()->json($response);
  325. }
  326. $message = 'Id tdak ditemukan';
  327. $response = [
  328. 'message' => $message,
  329. 'status' => false,
  330. ];
  331. return response()->json($response);
  332. }
  333. //custom route
  334. public function route()
  335. {
  336. return Route::group([
  337. 'as' => $this->route,
  338. 'prefix' => $this->url_prefix,
  339. 'namespace' => $this->namespace_controller
  340. ], function () {
  341. Route::get('/', ['as' => 'index', 'uses' => 'UserController@index']);
  342. Route::get('/create', ['as' => 'create', 'uses' => 'UserController@create']);
  343. Route::get('/update/{user_id}', ['as' => 'update', 'uses' => 'UserController@update']);
  344. Route::get('/delete-action/{user_id}', ['as' => 'delete_action', 'uses' => 'UserController@delete_action']);
  345. Route::get('/get-data', ['as' => 'get_data', 'uses' => 'UserController@getData']);
  346. Route::post('/create-action', ['as' => 'create_action', 'uses' => 'UserController@create_action']);
  347. Route::post('/update-action', ['as' => 'update_action', 'uses' => 'UserController@update_action']);
  348. });
  349. }
  350. //end custom route
  351. }