0% found this document useful (0 votes)
4 views19 pages

Visual Branding

The document outlines a CRUD (Create, Read, Update, Delete) implementation for managing 'Siswa' (students) and 'Course' data in a web application. It includes methods for creating, storing, updating, and deleting student and course records, as well as displaying them in a tabular format. Additionally, it features functionalities for importing Excel files, generating charts for subject distribution, and managing events on a calendar.

Uploaded by

delalex889
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Visual Branding

The document outlines a CRUD (Create, Read, Update, Delete) implementation for managing 'Siswa' (students) and 'Course' data in a web application. It includes methods for creating, storing, updating, and deleting student and course records, as well as displaying them in a tabular format. Additionally, it features functionalities for importing Excel files, generating charts for subject distribution, and managing events on a calendar.

Uploaded by

delalex889
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

CRUD SIswa:

Insert/Create:

public function create()

return view('admin.CreateSiswa'); // Create a form view

// Store a newly created siswa

public function store(Request $request)

// Custom validation messages

$messages = [

'StudentID.required' => 'The StudentID field is required.',

'StudentID.unique' => 'This StudentID already exists.',

'DOB.required' => 'The Date of Birth is required.',

'DOB.date' => 'The Date of Birth must be a valid date.',

'DOB.before' => 'The student must be at least 5 years old.',

'LastName.required' => 'The Last Name field is required.',

'FirstName.required' => 'The First Name field is required.',

// Add more messages as needed

];

// Validate the incoming request

$validated = $request->validate([

'StudentID' => 'required|unique:siswa,StudentID',

'DOB' => 'required|date|before:' . now()->subYears(5)->format('Y-m-d'),

'LastName' => 'required|string',

'FirstName' => 'required|string',

'Grade' => 'required|string',

'Gender' => 'required|string',


'Email' => 'required|email',

'SchoolName' => 'nullable|string',

'StreetName' => 'nullable|string',

'House' => 'nullable|string',

'City' => 'required|string',

'Province' => 'required|string',

'PostalCode' => 'required|string',

'HomePhone' => 'nullable|string',

'EnrolDate' => 'required|date',

'Subject' => 'required|string',

'CurrentLevel' => 'required|string',

], $messages);

// Process the transaction

try {

\DB::transaction(function () use ($request) {

$user = User::firstOrCreate(

['username' => $request->LastName],

['password' => Hash::make(Str::random(8)), 'role' => 'Customer']

);

Siswa::create([

'StudentID' => $request->StudentID,

'FirstName' => $request->FirstName,

'LastName' => $request->LastName,

'DOB' => $request->DOB,

'Grade' => $request->Grade,

'Gender' => $request->Gender,

'Email' => $request->Email,

'SchoolName' => $request->SchoolName,

'StreetName' => $request->StreetName,


'House' => $request->House,

'City' => $request->City,

'Province' => $request->Province,

'PostalCode' => $request->PostalCode,

'HomePhone' => $request->HomePhone,

'EnrolDate' => $request->EnrolDate,

'Subject' => $request->Subject,

'CurrentLevel' => $request->CurrentLevel,

'user_id' => $user->id_user,

]);

session()->flash('accountInfo', [

'username' => $user->username,

'password' => 'Account already exists or password generated during creation.',

]);

});

return redirect()->route('siswa.index')->with('success', 'Siswa created successfully.');

} catch (\Exception $e) {

return redirect()->route('siswa.index')->with('error', 'An error occurred: ' . $e->getMessage());

Di code ini terdapat validation terhadap semua column agar tiap column terisi dan tidak null, setelah
melakukan pengecekan diinsert ke database siswa dan user akan dikembalikan ke halaman master
siswa.

Update:

public function update(Request $request, $id)

$siswa = Siswa::findOrFail($id);

$siswa->update($request->all());

return redirect()->route('siswa.index')->with('success', 'Siswa updated successfully.');


}

Di code ini row dalam tabel siswa dilakukan update

Delete:

public function destroy($id)

$siswa = Siswa::findOrFail($id);

$siswa->delete(); // This will now perform a soft delete

return redirect()->route('siswa.index')->with('success', 'Siswa deleted successfully.');

Di code ini row tabel siswa dilakukan delete

Read:

public function index(Request $request)

return view('admin.MasterSiswa', compact('siswa'));

<table class="table table-bordered">

<thead>

<tr>

<th>Student ID</th>

<th>First Name</th>

<th>Last Name</th>

<th>DOB</th>

<th>Grade</th>

<th>Gender</th>

<th>Home Phone</th>

<th>Enrol Date</th>

<th>Subject</th>

<th>Current Level</th>
<th>Actions</th>

</tr>

</thead>

<tbody>

@foreach($siswa as $student)

<tr>

<td>{{ $student->StudentID }}</td>

<td>{{ $student->FirstName }}</td>

<td>{{ $student->LastName }}</td>

<td>{{ $student->DOB }}</td>

<td>{{ $student->Grade }}</td>

<td>{{ $student->Gender }}</td>

<td>{{ $student->HomePhone }}</td>

<td>{{ $student->EnrolDate }}</td>

<th>{{ $student->Subject }}</th>

<td>{{ $student->CurrentLevel }}</td>

<td>

<button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-


target="#viewMoreModal{{ $student->StudentID }}">

<i class="bi bi-eye"></i>

</button>

<a href="{{ route('siswa.edit', $student->StudentID) }}" class="btn btn-warning btn-


sm"><i class="bi bi-pencil"></i></a>

<a href="{{ route('siswa.edit-user', $student->StudentID) }}" class="btn btn-secondary


btn-sm"><i class="bi bi-person-fill-add"></i></a>

<form action="{{ route('siswa.destroy', $student->StudentID) }}" method="POST"


style="display: inline;">

@csrf

@method('DELETE')

<button type="submit" class="btn btn-danger btn-sm"><i class="bi


bi-trash"></i></button>
</form>

</a>

</a>

<!-- Modal -->

<div class="modal fade" id="viewMoreModal{{ $student->StudentID }}" tabindex="-1"


aria-labelledby="viewMoreModalLabel" aria-hidden="true">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h5 class="modal-title" id="viewMoreModalLabel">Details for {{ $student-


>FirstName }} {{ $student->LastName }}</h5>

<button type="button" class="btn-close" data-bs-dismiss="modal" aria-


label="Close"></button>

</div>

<div class="modal-body">

<p><strong>Student ID:</strong> {{ $student->StudentID }}</p>

<p><strong>Date of Birth:</strong> {{ $student->DOB }}</p>

<p><strong>Grade:</strong> {{ $student->Grade }}</p>

<p><strong>Gender:</strong> {{ $student->Gender }}</p>

<p><strong>Email:</strong> {{ $student->Email }}</p>

<p><strong>School Name:</strong> {{ $student->SchoolName }}</p>

<p><strong>Street Name:</strong> {{ $student->StreetName }}</p>

<p><strong>House:</strong> {{ $student->House }}</p>

<p><strong>City:</strong> {{ $student->City }}</p>

<p><strong>Province:</strong> {{ $student->Province }}</p>

<p><strong>Postal Code:</strong> {{ $student->PostalCode }}</p>

<p><strong>Home Phone:</strong> {{ $student->HomePhone }}</p>


<p><strong>Enrollment Date:</strong> {{ $student->EnrolDate }}</p>

<p><strong>Subject:</strong> {{ $student->Subject }}</p>

<p><strong>Current Level:</strong> {{ $student->CurrentLevel }}</p>

</div>

<div class="modal-footer">

<button type="button" class="btn btn-secondary" data-bs-


dismiss="modal">Close</button>

</div>

</div>

</div>

</div>

</td>

</tr>

@endforeach

</tbody>

</table>

Dilakukan passing variable di function index pada SiswaController terlebih dahulu, agar data column
dalam table siswa dapat ditampilkan dalam bentuk tabel dalam halaman MasterSiswa. Selain itu, ada
action button itu delete dan update serta modal view untuk detail lebih lanjut.

CRUD Course:

public function create()

return view('admin.InsertCourse');

public function store(Request $request)

$request->validate([
'course' => 'required|string|max:255',

'level' => 'required|string|max:255',

'description' => 'required|string|max:255',

]);

Course::create($request->all());

return redirect()->route('course.index')->with('success', 'Course added successfully.');

Di code ini diinsert ke database course dan user akan dikembalikan ke halaman master siswa.

Update:

public function update(Request $request, $idcourse)

$request->validate([

'course' => 'required|string|max:255',

'level' => 'required|string|max:255',

'description' => 'required|string|max:255',

]);

$course = Course::findOrFail($idcourse);

$course->update($request->all());

return redirect()->route('course.index')->with('success', 'Course updated successfully.');

Di code ini row dalam tabel course dilakukan update

Delete:
public function destroy($idcourse)

$course = Course::findOrFail($idcourse);

$course->delete();

return redirect()->route('course.index')->with('success', 'Course deleted successfully.');

Di code ini row dalam tabel course dilakukan delete

public function index(Request $request)

return view('admin.MasterCourse', compact('courses');

<table class="table table-bordered mt-3">

<tbody>

@foreach($courses as $course)

<tr>

<td>{{ $course->idcourse }}</td>

<td>{{ $course->course }}</td>

<td>{{ $course->level }}</td>

<td>{{ $course->description }}</td>

<td>

<a href="{{ route('course.edit', $course->idcourse) }}" class="btn btn-warning btn-sm"><i


class="bi bi-pencil"></i></a>

<form action="{{ route('course.destroy', $course->idcourse) }}" method="POST"


style="display: inline;">

@csrf

@method('DELETE')

<button type="submit" class="btn btn-danger btn-sm"><i class="bi bi-trash"></i></button>

</form>
</td>

</tr>

@endforeach

</tbody>

</table>

Dilakukan passing variable ke MasterCourse, lalu data tabel ditampilkan dalam bentuk table dalam
halaman MasterCourse

Code Chart:

// Subject Distribution Chart

const subjectCtx = document.getElementById('subjectChart').getContext('2d');

const subjectData = {

labels: @json($subjectCounts->pluck('Subject')),

datasets: [{

label: 'Students per Subject',

data: @json($subjectCounts->pluck('count')),

backgroundColor: ['#007bff', '#28a745', '#dc3545', '#ffc107', '#17a2b8'],

}]

};

const subjectChart = new Chart(subjectCtx, {

type: 'pie',

data: subjectData,

options: { responsive: true }

});

Menggunakan chart api, data diambil dari tabel siswa lalu ditampilkan dalam bentuk pie chart.

Calendar code:

$(document).ready(function () {

// Setup CSRF token for all AJAX requests

$.ajaxSetup({

headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

});

const calendar = $('#calendar').fullCalendar({

header: {

left: 'prev,next today',

center: 'title',

right: 'month,agendaWeek,agendaDay',

},

events: '/events', // Fetch events from the backend

dayClick: function (date, jsEvent, view) {

$('#eventDate').val(date.format('YYYY-MM-DD'));

$('#addEventModal').modal('show');

},

eventClick: function (event) {

if (confirm('Do you want to delete this event?')) {

$.ajax({

url: `/events/${event.id}`,

type: 'DELETE',

success: function () {

calendar.fullCalendar('removeEvents', event.id);

alert('Event deleted!');

},

error: function () {

alert('Failed to delete the event. Please try again.');

});

},

});
$('#eventForm').on('submit', function (event) {

event.preventDefault();

const title = $('#eventTitle').val();

const description = $('#eventDescription').val();

const date = $('#eventDate').val();

$.ajax({

url: '/events',

type: 'POST',

data: { title, description, event_date: date },

success: function (data) {

calendar.fullCalendar('renderEvent', {

id: data.id,

title: data.title,

start: data.event_date,

description: data.description,

color: '#007bff',

});

$('#addEventModal').modal('hide');

$('#eventForm')[0].reset();

},

error: function () {

alert('Failed to save the event. Please try again.');

});

});

});

Menggunakan fullcalendar api, bentuknya sebagai calendar academic dan bisa tambah dan delete
event sesuai tanggal. Event di simpan dalam database.
Import Excel:

public function importExcel(Request $request)

// Validate the file type

$request->validate([

'file' => 'required|mimes:xlsx,xls,csv',

]);

$file = $request->file('file');

try {

// Load the spreadsheet

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getRealPath());

$data = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

} catch (\Exception $e) {

\Log::error('Error loading file: ' . $e->getMessage());

return redirect()->route('siswa.index')->with('error', 'Failed to load Excel file.');

$importedCount = 0;

foreach ($data as $key => $row) {

if ($key == 1) continue; // Skip header row

try {

\Log::info("Processing row $key: ", $row);

// Check if the StudentID already exists

if (Siswa::where('StudentID', $row['A'])->exists()) {
\Log::info("Skipping duplicate StudentID on row $key: " . $row['A']);

continue; // Skip this row if StudentID already exists

// Create a new student record

Siswa::create([

'StudentID' => $row['A'],

'FirstName' => $row['B'],

'LastName' => $row['C'],

'DOB' => $this->parseDate($row['D']),

'Grade' => $row['E'],

'Gender' => $row['F'],

'Email' => $row['G'],

'SchoolName' => $row['H'],

'StreetName' => $row['I'],

'House' => $row['J'] ?? '', // Provide default value

'City' => $row['K'],

'Province' => $row['L'],

'PostalCode' => $row['M'],

'HomePhone' => $row['N'] ?? '',

'EnrolDate' => $this->parseDate($row['O']),

'Subject' => $row['P'],

'CurrentLevel' => $row['Q'] ?? 'A', // Default value if missing

]);

$importedCount++;

} catch (\Exception $e) {

\Log::error("Error on row $key: " . $e->getMessage());

return redirect()->route('siswa.index')->with('error', "Error on row $key: " . $e->getMessage());

}
\Log::info("Total records imported: $importedCount");

return redirect()->route('siswa.index')->with('success', "$importedCount records imported


successfully.");

Khusus untuk master siswa , dapat menerima extension xlsx, csv, xls dan data diimport ke tabel
siswa. Data diambil dari cell-cell yang ada di excel. Ada pengecekan bila terjadi error(primary key
kembar).

Export Excel:
public function exportExcel()

try {

$siswa = Siswa::all(); // Get all siswa records

if ($siswa->isEmpty()) {

// Log if no records found

Log::warning('No siswa records found for export.');

return response()->json(['message' => 'No data available for export.'], 204);

$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

$sheet = $spreadsheet->getActiveSheet();

// Set the header

$headers = [

'StudentID', 'FirstName', 'LastName', 'DOB', 'Grade',

'Gender', 'Email', 'SchoolName', 'StreetName',

'House', 'City', 'Province', 'PostalCode',

'HomePhone', 'EnrolDate', 'Subject', 'CurrentLevel',

];
$column = 'A'; // Start from column A

foreach ($headers as $header) {

$sheet->setCellValue($column . '1', $header); // Set the header in the first row

$column++;

// Fill the data

$row = 2; // Start from the second row

foreach ($siswa as $item) {

$sheet->setCellValue("A{$row}", $item->StudentID);

$sheet->setCellValue("B{$row}", $item->FirstName);

$sheet->setCellValue("C{$row}", $item->LastName);

$sheet->setCellValue("D{$row}", $item->DOB);

$sheet->setCellValue("E{$row}", $item->Grade);

$sheet->setCellValue("F{$row}", $item->Gender);

$sheet->setCellValue("G{$row}", $item->Email);

$sheet->setCellValue("H{$row}", $item->SchoolName);

$sheet->setCellValue("I{$row}", $item->StreetName);

$sheet->setCellValue("J{$row}", $item->House);

$sheet->setCellValue("K{$row}", $item->City);

$sheet->setCellValue("L{$row}", $item->Province);

$sheet->setCellValue("M{$row}", $item->PostalCode);

$sheet->setCellValue("N{$row}", $item->HomePhone);

$sheet->setCellValue("O{$row}", $item->EnrolDate);

$sheet->setCellValue("P{$row}", $item->Subject);

$sheet->setCellValue("Q{$row}", $item->CurrentLevel);

$row++;

// Save the file to a temporary location

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');


$filename = 'siswa_export_' . date('YmdHis') . '.xlsx';

$tempFilePath = storage_path("app/exports/{$filename}");

// Ensure the directory exists

if (!file_exists(dirname($tempFilePath))) {

mkdir(dirname($tempFilePath), 0755, true);

$writer->save($tempFilePath);

// Log the success message

Log::info("Siswa export completed successfully: {$filename}");

// Return the file as a download

return response()->download($tempFilePath)->deleteFileAfterSend(true);

} catch (\Exception $e) {

Log::error('Error exporting siswa data: ' . $e->getMessage());

return response()->json(['message' => 'An error occurred while exporting data.'], 500);

Khusus untuk master siswa , data diexport dari table siswa ke dalam bentuk csv.

Pagination, Filter, and Search:

public function index(Request $request)

$query = Siswa::query();

// Search by name or email

if ($request->filled('search')) {

$search = $request->search;

$query->where(function ($q) use ($search) {


$q->where('FirstName', 'like', "%$search%")

->orWhere('LastName', 'like', "%$search%")

->orWhere('Email', 'like', "%$search%");

});

// Filter by gender

if ($request->filled('gender')) {

$query->where('Gender', $request->gender);

// Filter by grade

if ($request->filled('grade')) {

$query->where('Grade', $request->grade);

// Determine the number of entries per page (default to 25)

$perPage = $request->input('per_page', 25);

// Get the filtered results with pagination

$siswa = $query->paginate($perPage)->appends($request->except('page'));

// Return view with filtered and/or searched data

return view('admin.MasterSiswa', compact('siswa'));

Function ini digunakan untuk fitur paginate, filter dan search

Breadcrumbs:

<script>

let currentFieldset = 0;

const fieldsets = document.querySelectorAll("fieldset");


const breadcrumbItems = document.querySelectorAll(".breadcrumb-item");

function showFieldset(index) {

fieldsets.forEach((fieldset, i) => {

fieldset.classList.toggle("active", i === index);

});

breadcrumbItems.forEach((item, i) => {

item.classList.toggle("active", i === index);

});

function nextFieldset() {

if (currentFieldset < fieldsets.length - 1) {

currentFieldset++;

showFieldset(currentFieldset);

function prevFieldset() {

if (currentFieldset > 0) {

currentFieldset--;

showFieldset(currentFieldset);

</script>

Code ini untuk fitur breadcrumb.

You might also like