user()->can('employees.view')) { return view("unauthorized.unauthorized"); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.employees'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); $employees = $trashed = $departments = $designations = $subjects = []; if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } if (request()->ajax()) { $employees = Employee::all(); $trashed = Employee::onlyTrashed()->get(); $response['homeData'] = view('employees.partials.home_data', compact('data', 'employees'))->render(); $response['trashData'] = view('employees.partials.trash_data', compact('data', 'trashed'))->render(); return response()->json($response); } // Fetch employees, departments, designations, subjects, and trashed employees for non-AJAX request $employees = Employee::all(); $departments = EmployeeDepartment::all(); $designations = EmployeeDesignation::all(); $subjects = Subject::all(); $trashed = Employee::onlyTrashed()->get(); return view('employees.index', compact('data', 'employees', 'trashed', 'departments', 'designations', 'subjects')); } /** * Show the form for creating a new resource. */ public function create() { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.create'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); // Check if the user has the role 'Super Admin' and fetch all businesses if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->where('users.business_id', auth()->user()->business_id) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); $marital_statuses = MaritalStatus::all(); $referencers = UserReferencer::all(); $employee_departments = EmployeeDepartment::all(); $employee_designations = EmployeeDesignation::all(); $subjects = Subject::all(); $user_types = UserType::all(); // Pass the data to the view return view('employees.create', compact('data', 'users', 'marital_statuses', 'employee_departments', 'employee_designations', 'user_types', 'referencers', 'subjects'))->render(); } //new public function store(EmployeeRequest $request) { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } // Begin a database transaction DB::beginTransaction(); try { // Get validated data $validatedData = $request->validated(); // Extract data for each model $employeeData = [ 'business_id' => $validatedData['business_id'], 'user_id' => $validatedData['user_id'], 'type_id' => $validatedData['type_id'], 'employee_information_id' => null, 'reference_id' => $validatedData['reference_id'], 'marital_status_id' => $validatedData['marital_status_id'], 'designation_id' => $validatedData['designation_id'], 'note' => $validatedData['note'], ]; $empExperiance = [ 'institution_name' => $validatedData['institution_name'], 'designation' => $validatedData['designation'], 'location' => $validatedData['location'], 'start_date' => $validatedData['start_date'], 'end_date' => $validatedData['end_date'], 'responsibility' => $validatedData['responsibility'], 'note' => $validatedData['note_exp'], ]; $empInformation = [ 'designation_id' => $validatedData['designation_id'], 'department_id' => $validatedData['department_id'], 'in_time' => $validatedData['in_time'], 'out_time' => $validatedData['out_time'], 'preference_subject_id' => $validatedData['preference_subject_id'], 'work_phone_no' => $validatedData['work_phone_no'], 'note' => $validatedData['note_info'], ]; // Store data in respective tables $experience = EmployeeExperience::create($empExperiance); $information = EmployeeInformations::create($empInformation); Employee::create(array_merge($employeeData, ['experience_id' => $experience->id, 'employee_information_id' => $information->id])); // Commit the transaction DB::commit(); $output = [ 'success' => true, 'msg' => __('core.added_successfully'), ]; } catch (\Exception $e) { // Rollback the transaction if there is an error DB::rollBack(); \Log::error('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } // Redirect to the employee index page with output message return redirect()->route('employees.index')->with('output', $output); } /** * Display the specified resource. */ public function show(string $id) { if (!auth()->user()->can('employees.view')) { return view("unauthorized.unauthorized"); } } /** * Show the form for editing the specified resource. */ public function edit(string $id) { if (!auth()->user()->can('employees.update')) { return view("unauthorized.unauthorized"); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.update'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); $employee = Employee::with('information', 'experience')->findOrFail($id); $businesses = []; if (auth()->user()->hasRole('Super Admin')) { $businesses = Business::all(); } // Fetch other data needed for the form $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); // $users = User::all(); $marital_statuses = MaritalStatus::all(); $referencers = UserReferencer::all(); $employee_departments = EmployeeDepartment::all(); $employee_designations = EmployeeDesignation::all(); $subjects = Subject::all(); $user_types = UserType::all(); // dd($subjects); // dd($employee->information); // Pass all data to the view return view('employees.edit', compact('data', 'employee', 'businesses', 'users', 'marital_statuses', 'employee_departments', 'employee_designations', 'user_types', 'referencers', 'subjects'))->render(); } /** * Update the specified resource in storage. */ public function update(EmployeeRequest $request, string $id) { if (!auth()->user()->can('employees.update')) { return view("unauthorized.unauthorized"); } // return "b"; // dd($request->all()); // dd($request); DB::beginTransaction(); try { // Validate the request // $validatedData = $request->all(); $validatedData = $request->validated(); // $validatedData = $request->validated(); // Fetch the existing employee record $employee = Employee::findOrFail($id); // dd($employee); // Update Employee basic data $employeeData = [ 'business_id' => $validatedData['business_id'], 'user_id' => $validatedData['user_id'], 'type_id' => $validatedData['type_id'], 'reference_id' => $validatedData['reference_id'], 'marital_status_id' => $validatedData['marital_status_id'], 'designation_id' => $validatedData['designation_id'], 'note' => $validatedData['note'], ]; $employee->update($employeeData); // Update or create EmployeeExperience $experienceData = [ 'institution_name' => $validatedData['institution_name'], 'designation' => $validatedData['designation'], 'location' => $validatedData['location'], 'start_date' => $validatedData['start_date'], 'end_date' => $validatedData['end_date'], 'responsibility' => $validatedData['responsibility'], 'note' => $validatedData['note_exp'], ]; if ($employee->experience) { $employee->experience->update($experienceData); } else { $experience = $employee->experience()->create($experienceData); $employee->update(['experience_id' => $experience->id]); } // Update or create EmployeeInformations $informationData = [ 'designation_id' => $validatedData['designation_id'], 'department_id' => $validatedData['department_id'], 'in_time' => $validatedData['in_time'], 'out_time' => $validatedData['out_time'], 'preference_subject_id' => $validatedData['preference_subject_id'], 'work_phone_no' => $validatedData['work_phone_no'], 'note' => $validatedData['note_info'], ]; if ($employee->information) { $employee->information->update($informationData); } else { $information = $employee->information()->create($informationData); $employee->update(['employee_information_id' => $information->id]); } // Commit the transaction DB::commit(); // Success response $output = [ 'success' => true, 'msg' => __('core.updated_success'), ]; } catch (\Exception $e) { // Rollback the transaction if there is an error DB::rollBack(); \Log::error('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage()); // Error response $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } // Redirect to the employee index page with output message return redirect()->route('employees.index')->with('output', $output); } // toggole status public function toggleStatus(Request $request, $id) { if (!auth()->user()->can('employees.toggle')) { return view("unauthorized.unauthorized"); } try { $employee = Employee::findOrFail($id); // Ensure using the request ID $status = $employee->status == '1' ? '0' : '1'; // Toggle status $updated = $employee->update(['status' => $status]); // Update and check result $output = [ 'success' => true, 'msg' => __('core.updated_successfully'), ]; } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('messages.something_went_wrong'), ]; } return response()->json($output); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { if (!auth()->user()->can('employees.delete')) { return view("unauthorized.unauthorized"); } try { $employee = Employee::findOrFail($id); $employee->delete(); } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } return route('employees.index'); } /** * Restore a specific resource. */ public function restore($id) { if (!auth()->user()->can('employees.delete')) { return view("unauthorized.unauthorized"); } try { Employee::restoreById($id); $output = [ 'success' => true, 'msg' => __('employees_restored_success'), ]; } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } return response()->json($output); } /** * Permanently delete a specific resource. */ public function delete($id) { if (!auth()->user()->can('employees.trash_delete')) { return view("unauthorized.unauthorized"); } try { Employee::forceDeleteById($id); $output = [ 'success' => true, 'msg' => __('Employee_force_delete_success'), ]; } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } return response()->json($output); } public function employeeDetails($id) { // Fetch the specific employee by ID $employee = Employee::findOrFail($id); // Fetch related data $marital_statuses = MaritalStatus::all(); // Fetch all marital statuses $referencers = UserReferencer::all(); // Fetch all referencers $employee_departments = EmployeeDepartment::all(); // Fetch all employee departments $employee_designations = EmployeeDesignation::all(); // Fetch all employee designations $subjects = Subject::all(); // Fetch all subjects $user_types = UserType::all(); // Fetch all user types // Pass the data to the view return view('employees.details', compact( 'employee', 'marital_statuses', 'referencers', 'employee_departments', 'employee_designations', 'subjects', 'user_types' )); } /** * Upload a file. */ private function _uploadImage(Request $request) { try { $request->validate([ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $path = $image->storeAs('public/images', $filename); $imageUrl = Storage::url($path); return [ 'success' => true, 'url' => $imageUrl, 'filename' => $filename, ]; } catch (\Exception $e) { return [ 'success' => false, 'message' => $e->getMessage(), 'error' => true, ]; } } // Private method for save or update logic private function _saveOrUpdateEmployeeExperience(Request $request, $id = null) { $input = $request->input('employee_experiences'); // Formatting dates if (!empty($input['start_date'])) { $date = \DateTime::createFromFormat('m/d/Y', $input['start_date']); $formattedDate = $date->format('Y-m-d'); $input['start_date'] = $formattedDate; } if (!empty($input['end_date'])) { $date = \DateTime::createFromFormat('m/d/Y', $input['end_date']); $formattedDate = $date->format('Y-m-d'); $input['end_date'] = $formattedDate; } if ($id) { // Update the existing record $experience = EmployeeExperience::find($id); if ($experience) { $experience->update($input); } } else { $experience = EmployeeExperience::create($input); return $experience->id; } return null; } private function _saveOrUpdateEmployeeInformation(Request $request, $id = null) { $input = $request->input('employee_informations'); // format time if (!empty($input['in_time'])) { $time = date('H:i:s', strtotime($input['in_time'])); // Convert input time to MySQL time format $input['in_time'] = $time; } // format time if (!empty($input['out_time'])) { $time = date('H:i:s', strtotime($input['out_time'])); // Convert input time to MySQL time format $input['out_time'] = $time; } if ($id) { // Update the existing record $information = EmployeeInformations::find($id); if ($information) { $information->update($input); } } else { $information = EmployeeInformations::create($input); return $information->id; } return null; } public function employeeImportExcel() { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } return view('employees.excel'); } public function employeeExportExcel() { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } return Excel::download(new EmployeePartialExport, 'employeesPartials.xlsx'); } public function employeeExportExcelHeadings() { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } return Excel::download(new EmployeeHeadingsExport, 'employeesHeadings.xlsx'); } public function employeesImportExcelPost(Request $request) { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } $request->validate([ 'file' => 'required|mimes:xlsx,xls', ]); $busniess_id = auth()->user()->business_id; try { // Import the file Excel::import(new EmployeesImport($busniess_id), $request->file('file')); return redirect()->back()->with('success', 'Employees Imported Successfully'); } catch (\Maatwebsite\Excel\Validators\ValidationException $e) { // dd(session()->all()); // Get validation errors $failures = $e->failures(); foreach ($failures as $failure) { \Log::error('Validation failure:', [ 'row' => $failure->row(), 'attribute' => $failure->attribute(), 'errors' => $failure->errors(), ]); } // Redirect back with errors return back()->withErrors($failures)->withInput(); } } public function employeeSearch(Request $request) { try { $query = Employee::query(); if ($request->filled('business_id')) { $query->where('business_id', $request->business_id); } if ($request->type_id == 1) { $query->where('type_id', 1); } elseif ($request->type_id == 2) { $query->where('type_id', 2); } $query->whereHas('information', function ($query) use ($request) { if ($request->department_id != null) { $query->where('department_id', $request->department_id); } if ($request->designation_id != null) { $query->where('designation_id', $request->designation_id); } if ($request->preference_subject_id != null) { $query->where('preference_subject_id', $request->preference_subject_id); } }); $employees = $query->get(); // trashed data $trashedQuery = Employee::onlyTrashed(); if ($request->filled('business_id')) { $trashedQuery->where('business_id', $request->business_id); } if ($request->type_id == 1) { $trashedQuery->where('type_id', 1); } elseif ($request->type_id == 2) { $trashedQuery->where('type_id', 2); } $trashedQuery->whereHas('information', function ($trashedQuery) use ($request) { if ($request->department_id != null) { $trashedQuery->where('department_id', $request->department_id); } if ($request->designation_id != null) { $trashedQuery->where('designation_id', $request->designation_id); } if ($request->preference_subject_id != null) { $trashedQuery->where('preference_subject_id', $request->preference_subject_id); } }); $trashed = $trashedQuery->get(); $response['homeData'] = view('employees.partials.home_data', compact('employees'))->render(); $response['trashData'] = view('employees.partials.trash_data', compact('trashed'))->render(); return response()->json($response); } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage()); $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; return response()->json($output); } } public function exportEmployeesdata() { if (!auth()->user()->can('employees.view')) { return view("unauthorized.unauthorized"); } return Excel::download(new ExportEmployeesData, 'employees_data.xlsx'); } public function user_employee_create() { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.create'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); // Check if the user has the role 'Super Admin' and fetch all businesses if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->where('users.business_id', auth()->user()->business_id) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); $marital_statuses = MaritalStatus::all(); $referencers = UserReferencer::all(); $employee_departments = EmployeeDepartment::all(); $employee_designations = EmployeeDesignation::all(); $subjects = Subject::all(); $user_types = UserType::all(); if (!auth()->user()->can('users.create')) { return response('Unauthorized', 403); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('user.create'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } $addresses = AddressController::formatAddressWithLatest(auth()->user()->business_id); $nationalities = Nationality::all(); $religions = Religion::all(); if (auth()->user()->hasRole('Super Admin')) { $roles = Role::all(); } else { $roles = Role::where('business_id', auth()->user()->business_id)->get(); } // Pass the data to the view return view("employees.user_employee_create", compact('data', 'users', 'marital_statuses', 'employee_departments', 'employee_designations', 'user_types', 'referencers', 'subjects', 'roles', 'addresses', 'nationalities', 'religions'))->render(); } public function getUsersForEmployeeCreate(Request $request) { $business_id = auth()->user()->business_id; if (auth()->user()->hasRole('Super Admin')) { $business_id = $request->input("business_id"); } $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->where('users.business_id', $business_id) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); return response()->json(['users' => $users]); } public function load_employee_form_data_by_user(Request $request) { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } $business_id = $request->input("business_id") ?? auth()->user()->business_id; $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.create'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); // Check if the user has the role 'Super Admin' and fetch all businesses if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->where('users.business_id', $business_id) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); $marital_statuses = MaritalStatus::all(); $referencers = UserReferencer::all(); $employee_departments = EmployeeDepartment::where("business_id", $business_id)->get(); $employee_designations = EmployeeDesignation::where("business_id", $business_id)->get(); $subjects = Subject::where("business_id", $business_id)->get(); $user_types = UserType::where("business_id", $business_id)->get(); if (!auth()->user()->can('users.create')) { return response('Unauthorized', 403); } if (auth()->user()->hasRole('Super Admin')) { $data['businesses'] = Business::all(); } $addresses = AddressController::formatAddressWithLatest($business_id); $nationalities = Nationality::all(); $religions = Religion::all(); if (auth()->user()->hasRole('Super Admin')) { $roles = Role::all(); } else { $roles = Role::where('business_id', $business_id)->get(); } $step = 'step-2'; $created_user = User::find($request->input("user_id")); // Pass the data to the view return view('employees.user_employee_create', compact('data', 'users', 'marital_statuses', 'employee_departments', 'employee_designations', 'user_types', 'referencers', 'subjects', 'roles', 'addresses', 'nationalities', 'religions', 'step', 'created_user', 'business_id'))->render(); } public function user_store(UserRequest $request) { if (!auth()->user()->can('users.create')) { return view("unauthorized.unauthorized"); } $created_user = null; $business_id = $request->input("business_id") ?? auth()->user()->business_id; $step = 'step-1'; try { $validatedData = $request->validated(); if ($request->hasFile('birth_certificate')) { $validatedData['birth_certificate'] = $request->file('birth_certificate')->store('public/uploads/users/birth_certificates'); } if ($request->hasFile('photo')) { $validatedData['photo'] = $request->file('photo')->store('public/uploads/users/photos'); } // Create the user $user = User::create($validatedData); $created_user = $user; // Assign roles using role IDs $roleNames = $request->input('roles') ?? []; // Get the corresponding role IDs from the database $roleIds = Role::whereIn('name', $roleNames)->pluck('id')->toArray(); // insert the new roles foreach ($roleIds as $roleId) { FacadesDB::table('model_has_roles')->insert([ 'model_id' => $user->id, 'model_type' => 'App\Models\User', 'role_id' => $roleId, ]); } $step = 'step-2'; $output = [ 'success' => true, 'msg' => __('core.added_successfully'), 'business_id' => $business_id, 'user_id' => $user->id, 'step' => $step ]; } catch (\Exception $e) { \Log::emergency('File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage()); $step = 'step-1'; $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), 'step' => $step, 'er' => 'File:' . $e->getFile() . 'Line:' . $e->getLine() . 'Message:' . $e->getMessage() ]; } return response()->json($output); // return view('students.user_student_create', compact('data', 'users', 'groups', 'academic_year', 'shifts', 'student_statuses', 'user_types', 'blood_groups', 'special_user_types', 'sections', 'academic_classes', 'references', 'guardians', 'students', 'relationTypes', 'roles', 'addresses', 'nationalities', 'religions', 'business_id', 'created_user', 'step'))->render(); } public function employee_store(EmployeeRequest $request) { if (!auth()->user()->can('employees.create')) { return view("unauthorized.unauthorized"); } // Begin a database transaction DB::beginTransaction(); $step = "step-2"; try { // Get validated data $validatedData = $request->validated(); // Extract data for each model $employeeData = [ 'business_id' => $validatedData['business_id'], 'user_id' => $validatedData['user_id'], 'type_id' => $validatedData['type_id'], 'employee_information_id' => null, 'reference_id' => $validatedData['reference_id'], 'marital_status_id' => $validatedData['marital_status_id'], 'designation_id' => $validatedData['designation_id'], 'note' => $validatedData['note'], ]; $empExperiance = [ 'institution_name' => $validatedData['institution_name'], 'designation' => $validatedData['designation'], 'location' => $validatedData['location'], 'start_date' => $validatedData['start_date'], 'end_date' => $validatedData['end_date'], 'responsibility' => $validatedData['responsibility'], 'note' => $validatedData['note_exp'], ]; $empInformation = [ 'designation_id' => $validatedData['designation_id'], 'department_id' => $validatedData['department_id'], 'in_time' => $validatedData['in_time'], 'out_time' => $validatedData['out_time'], 'preference_subject_id' => $validatedData['preference_subject_id'], 'work_phone_no' => $validatedData['work_phone_no'], 'note' => $validatedData['note_info'], ]; // Store data in respective tables $experience = EmployeeExperience::create($empExperiance); $information = EmployeeInformations::create($empInformation); Employee::create(array_merge($employeeData, ['experience_id' => $experience->id, 'employee_information_id' => $information->id])); // Commit the transaction DB::commit(); $step = "step-3"; $output = [ 'success' => true, 'msg' => __('core.added_successfully'), 'step' => $step ]; } catch (\Exception $e) { // Rollback the transaction if there is an error DB::rollBack(); \Log::error('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage()); $step = "step-2"; $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), 'step' => $step ]; } // $data = [ // "output"=>$output, // "step"=>$step, // ]; return response()->json($output); } public function user_employee_edit($id) { if (!auth()->user()->can('employees.update')) { return view("unauthorized.unauthorized"); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('employee.update'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); $employee = Employee::with('information', 'experience')->findOrFail($id); $businesses = []; if (auth()->user()->hasRole('Super Admin')) { $businesses = Business::all(); } $data = session('data'); // Do something with the data $output = null; $step = null; if ($data) { $output = $data['output'] ?? null; $step = $data['step'] ?? null; } // Unset the session data session()->forget('data'); // Fetch other data needed for the form $users = User::leftJoin('students', 'users.id', '=', 'students.user_id') // Joining the `students` table ->leftJoin('employees', 'users.id', '=', 'employees.user_id') // Joining the `employees` table ->leftJoin('guardians', 'users.id', '=', 'guardians.user_id') // Joining the `guardians` table ->whereNull('students.id') // Exclude users who have a student profile ->where(function ($query) { $query->whereNull('employees.id') // Exclude users who have an employee profile ->orWhereNotIn('employees.type_id', [1, 2]); // Exclude teachers (type_id = 1) and employees (type_id = 2) }) ->whereNull('guardians.id') // Exclude users who have a guardian profile ->select('users.*') ->distinct() // Ensure unique users ->get(); // $users = User::all(); $marital_statuses = MaritalStatus::all(); $referencers = UserReferencer::all(); $employee_departments = EmployeeDepartment::all(); $employee_designations = EmployeeDesignation::all(); $subjects = Subject::all(); $user_types = UserType::all(); // dd($subjects); if (!auth()->user()->can('users.update')) { return response('Unauthorized', 403); } $currentRoute = Route::currentRouteName(); $data['route'] = $currentRoute; $data['title'] = __('user.update'); $data['is_favourite'] = FavouriteMenu::where('route', $currentRoute)->exists(); $businesses = []; if (auth()->user()->hasRole('Super Admin')) { $businesses = Business::all(); } $user = User::findOrFail($employee->user_id); // Get user's present address $currentAddressId = $user->present_address_id; //new // Fetch all addresses and map to include full_address $addresses = Address::all()->map(function ($address) { return ['id' => $address->id, 'full_address' => $address->full_address]; }); $nationalities = Nationality::all(); $religions = Religion::all(); if (auth()->user()->hasRole('Super Admin')) { $roles = Role::all(); } else { $roles = Role::where('business_id', auth()->user()->business_id)->get(); } $userRoles = $user->roles->pluck('name')->toArray(); // return view('users.edit', compact( // 'data', // 'businesses', // 'user', // 'addresses', // 'currentAddressId', // 'nationalities', // 'religions', // 'roles', // 'userRoles' // )); return view('employees.user_employee_edit', compact( 'data', 'employee', 'businesses', 'users', 'marital_statuses', 'employee_departments', 'employee_designations', 'user_types', 'referencers', 'subjects', 'user', 'addresses', 'currentAddressId', 'nationalities', 'religions', 'roles', 'userRoles', "output", "step", ))->render(); } public function user_employee_update_user(UserRequest $request, $user_id, $employee_id) { if (!auth()->user()->can('users.update')) { return view("unauthorized.unauthorized"); } $step = "step-1"; try { // Find the user by ID $user = User::findOrFail($user_id); // Validate and retrieve the input data $validatedData = $request->validated(); // Update photo if ($request->hasFile('photo')) { if ($user->photo && Storage::exists($user->photo)) { Storage::delete($user->photo); // Delete old file } $user->update(['photo' => $request->file('photo')->store('public/uploads/users/photos')]); // Store new file } // Update birth certificate if ($request->hasFile('birth_certificate')) { if ($user->birth_certificate && Storage::exists($user->birth_certificate)) { Storage::delete($user->birth_certificate); // Delete old file } $user->update(['birth_certificate' => $request->file('birth_certificate')->store('public/uploads/users/birth_certificates')]); // Store new file } // Update user data $user->update($validatedData); // Get the role names from the request $roleNames = $request->input('roles') ?? []; // Get the corresponding role IDs from the database $roleIds = Role::whereIn('name', $roleNames)->pluck('id')->toArray(); // First, remove all the previous roles associated with the user FacadesDB::table('model_has_roles') ->where('model_id', $user->id) ->where('model_type', 'App\Models\User') ->delete(); // Then, insert the new roles foreach ($roleIds as $roleId) { FacadesDB::table('model_has_roles')->insert([ 'model_id' => $user->id, 'model_type' => 'App\Models\User', 'role_id' => $roleId, ]); } // // Assign User Role part // $roleNames = $request->input('roles'); // $roleIds = Role::whereIn('name', $roleNames)->pluck('id')->toArray(); // // Attach roles // $user->syncRoles($roleIds); // // Update `model_type` directly in `model_has_roles` table // FacadesDB::table('model_has_roles') // ->where('model_id', $user->id) // ->update(['model_type' => 'App\Models\User']); $step = "step-2"; $output = [ 'success' => true, 'msg' => __('core.updated_success'), // Assuming you have a translation for updated success ]; } catch (\Exception $e) { \Log::emergency('File: ' . $e->getFile() . ' Line: ' . $e->getLine() . ' Message: ' . $e->getMessage()); $step = "step-1"; $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } $data = [ "output" => $output, "step" => $step ]; return redirect()->to(route('employees.user_employee_edit', ["id" => $employee_id]) . "#" . $step)->with('data', $data); } public function user_employee_update_employee(EmployeeRequest $request, $id) { if (!auth()->user()->can('employees.update')) { return view("unauthorized.unauthorized"); } $output = null; $step = "step-2"; // return "b"; // dd($request->all()); // dd($request); DB::beginTransaction(); try { // Validate the request // $validatedData = $request->all(); $validatedData = $request->validated(); // $validatedData = $request->validated(); // Fetch the existing employee record $employee = Employee::findOrFail($id); // dd($employee); // Update Employee basic data $employeeData = [ 'business_id' => $validatedData['business_id'], 'user_id' => $validatedData['user_id'], 'type_id' => $validatedData['type_id'], 'reference_id' => $validatedData['reference_id'], 'marital_status_id' => $validatedData['marital_status_id'], 'designation_id' => $validatedData['designation_id'], 'note' => $validatedData['note'], ]; $employee->update($employeeData); // Update or create EmployeeExperience $experienceData = [ 'institution_name' => $validatedData['institution_name'], 'designation' => $validatedData['designation'], 'location' => $validatedData['location'], 'start_date' => $validatedData['start_date'], 'end_date' => $validatedData['end_date'], 'responsibility' => $validatedData['responsibility'], 'note' => $validatedData['note_exp'], ]; if ($employee->experience) { $employee->experience->update($experienceData); } else { $experience = $employee->experience()->create($experienceData); $employee->update(['experience_id' => $experience->id]); } // Update or create EmployeeInformations $informationData = [ 'designation_id' => $validatedData['designation_id'], 'department_id' => $validatedData['department_id'], 'in_time' => $validatedData['in_time'], 'out_time' => $validatedData['out_time'], 'preference_subject_id' => $validatedData['preference_subject_id'], 'work_phone_no' => $validatedData['work_phone_no'], 'note' => $validatedData['note_info'], ]; if ($employee->information) { $employee->information->update($informationData); } else { $information = $employee->information()->create($informationData); $employee->update(['employee_information_id' => $information->id]); } // Commit the transaction DB::commit(); // Success response $step = "step-3"; $output = [ 'success' => true, 'msg' => __('core.updated_success'), ]; } catch (\Exception $e) { // Rollback the transaction if there is an error DB::rollBack(); \Log::error('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage()); // Error response $step = "step-2"; $output = [ 'success' => false, 'msg' => __('core.something_went_wrong'), ]; } $data = [ "output" => $output, "step" => $step ]; // Redirect to the employee index page with output message return redirect()->to(route('employees.user_employee_edit', ["id" => $id]) . "#" . $step)->with('data', $data); } }