Commit 65e77812 by Amshar

DATABASE RELATIONSHIP

parent 3125046c
...@@ -13,7 +13,10 @@ class DepartmentController extends Controller ...@@ -13,7 +13,10 @@ class DepartmentController extends Controller
*/ */
public function index() public function index()
{ {
$departments = Department::orderBy('name')->paginate(10); // sorts departments alphabetically so the list looks organised and fetches only 10 rows per page. // withCount('staff') adds a staff_count column to each department
// using a single COUNT query, without loading any actual staff records.
// Think of it like asking "how many?" instead of "give me everyone's details."
$departments = Department::withCount('staff')->orderBy('name')->paginate(10);
return view('departments.index', compact('departments')); // passes the $departments variable to the view. return view('departments.index', compact('departments')); // passes the $departments variable to the view.
} }
...@@ -58,7 +61,13 @@ public function store(Request $request) ...@@ -58,7 +61,13 @@ public function store(Request $request)
*/ */
public function show(Department $department) public function show(Department $department)
{ {
return view('departments.show', compact('department')); // To display one record in the database // load() eager-loads the staff relationship on a model you already have.
// The closure sorts them by name so the list looks tidy.
// Without this, accessing $department->staff in the view would still work,
// but it would run a separate query for each staff member (the N+1 problem).
$department->load(['staff' => fn ($q) => $q->orderBy('name')]);
return view('departments.show', compact('department'));
} }
/** /**
...@@ -92,8 +101,16 @@ public function update(Request $request, Department $department) ...@@ -92,8 +101,16 @@ public function update(Request $request, Department $department)
*/ */
public function destroy(Department $department) public function destroy(Department $department)
{ {
$department->delete(); // Deelete the department chosen // Check if this department still has any staff linked to it.
// staff() with parentheses gives a query builder, and exists()
// runs a quick check without loading all the staff records.
// This catches the problem BEFORE MySQL throws an error.
if ($department->staff()->exists()) {
return back()->with('error', 'Move or remove its staff first.');
}
$department->delete();
return back()->with('success', 'Department deleted.'); // back() is used instead of redirect()->route(...) because the user might be deleting from page 3 of the list, and you want them to stay on page 3 rather than jumping back to page 1. return back()->with('success', 'Department deleted.');
} }
} }
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory; // imports the HasFactory trait, which lets you call Department::factory() to generate fake data. Without this line, the factory connection wouldn't work. use Illuminate\Database\Eloquent\Factories\HasFactory; // imports the HasFactory trait, which lets you call Department::factory() to generate fake data. Without this line, the factory connection wouldn't work.
use Illuminate\Database\Eloquent\Model; // imports Laravel's base Model class. This is what gives your Department all the built-in powers like find(), create(), update(), delete(), where(), and everything else you've been using in Tinker. use Illuminate\Database\Eloquent\Model; // imports Laravel's base Model class. This is what gives your Department all the built-in powers like find(), create(), update(), delete(), where(), and everything else you've been using in Tinker.
use Illuminate\Database\Eloquent\Relations\HasMany; // imports the HasMany return type so Laravel knows what staff() gives back
class Department extends Model // creates your Department class and inherits everything from Model. By convention, Laravel sees the name "Department" and automatically connects it to the departments table in MySQL. class Department extends Model // creates your Department class and inherits everything from Model. By convention, Laravel sees the name "Department" and automatically connects it to the departments table in MySQL.
{ {
...@@ -15,4 +16,15 @@ class Department extends Model // creates your Department class and inherits eve ...@@ -15,4 +16,15 @@ class Department extends Model // creates your Department class and inherits eve
'description', 'description',
'is_active', 'is_active',
]; ];
}
/**
* A department has many staff members.
* This is the other side of the relationship — from the "one" looking
* down at the "many". Laravel knows to look for department_id on the
* staff table because this model is called Department.
*/
public function staff(): HasMany
{
return $this->hasMany(Staff::class);
}
}
\ No newline at end of file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Staff extends Model
{
/** @use HasFactory<\Database\Factories\StaffFactory> */
use HasFactory;
// Only these fields can be mass-assigned with create() or update().
// Anything not listed here is silently ignored, which protects
// against someone sneaking extra fields into a form submission.
protected $fillable = [
'department_id',
'staff_no',
'name',
'email',
'position',
'join_date',
];
/**
* A staff member belongs to one department.
* Laravel looks for a department_id column on this table
* and matches it to the id column on the departments table.
*/
public function department(): BelongsTo
{
return $this->belongsTo(Department::class);
}
}
\ No newline at end of file
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
"laravel/tinker": "^3.0" "laravel/tinker": "^3.0"
}, },
"require-dev": { "require-dev": {
"barryvdh/laravel-debugbar": "^4.4",
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.5", "laravel/pail": "^1.2.5",
"laravel/pao": "^1.0.6", "laravel/pao": "^1.0.6",
......
<?php
namespace Database\Factories;
use App\Models\Department;
use App\Models\Staff;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Staff>
*/
class StaffFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
// If no department is provided, the factory creates one automatically.
// In our seeder we'll override this with a real department ID.
'department_id' => Department::factory(),
// bothify() replaces # with a random digit, so S-#### becomes something like S-4821.
// unique() makes sure no two staff share the same number in one seeder run.
'staff_no' => fake()->unique()->bothify('S-####'),
// A realistic full name like "Aina Rahman" or "John Smith"
'name' => fake()->name(),
// A safe email that won't accidentally send to a real address (uses @example.com)
'email' => fake()->unique()->safeEmail(),
// A random job title like "Accountant" or "Software Engineer"
'position' => fake()->jobTitle(),
// A random date within the last 5 years, so join dates look realistic
'join_date' => fake()->dateTimeBetween('-5 years'),
];
}
}
\ No newline at end of file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('staff', function (Blueprint $table) {
// Primary key, auto-incrementing
$table->id();
// Foreign key linking each staff member to a department.
// foreignId() creates an unsigned big integer column matching departments.id.
// constrained() tells Laravel to look up the departments table automatically.
// restrictOnDelete() prevents deleting a department that still has staff.
$table->foreignId('department_id')
->constrained()
->restrictOnDelete();
// Staff number like S-0101, must be unique across the company
$table->string('staff_no', 20)->unique();
// Full name of the staff member
$table->string('name', 100);
// Work email, also unique so no two staff share one
$table->string('email')->unique();
// Job title or role within the department
$table->string('position', 100);
// The date this person joined the company (not a datetime, just the calendar date)
$table->date('join_date');
// created_at and updated_at, managed by Laravel automatically
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('staff');
}
};
\ No newline at end of file
...@@ -26,6 +26,7 @@ public function run(): void ...@@ -26,6 +26,7 @@ public function run(): void
DepartmentSeeder::class, DepartmentSeeder::class,
PositionSeeder::class, PositionSeeder::class,
UserSeeder::class, UserSeeder::class,
StaffSeeder::class, // must come after DepartmentSeeder
]); ]);
} }
} }
\ No newline at end of file
...@@ -45,7 +45,9 @@ public function run(): void // method Laravel calls when you tell it to seed the ...@@ -45,7 +45,9 @@ public function run(): void // method Laravel calls when you tell it to seed the
'is_active' => true, 'is_active' => true,
]); ]);
Department::factory()->count(50)->create(); //Department::factory()->count(50)->create(); (discomment this if you want to generate 50 departments into the database)
// Factory rows removed — Week 6 seeds 10 staff per department,
// so we keep only the 5 real ones above.
/* /*
Department::factory() says "use the DepartmentFactory to generate fake data" Department::factory() says "use the DepartmentFactory to generate fake data"
......
<?php
namespace Database\Seeders;
use App\Models\Department;
use App\Models\Staff;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class StaffSeeder extends Seeder
{
/**
* Seed 10 staff members into each existing department.
* We loop through every department and use the factory to create 10 staff,
* but we override department_id so they join the real department
* instead of the factory creating a random new one.
*/
public function run(): void
{
Department::all()->each(function ($department) {
Staff::factory(10)->create([
'department_id' => $department->id,
]);
});
}
}
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
<tr> <tr>
<th>Code</th> {{--Column Code--}} <th>Code</th> {{--Column Code--}}
<th>Name</th> {{--Column Name--}} <th>Name</th> {{--Column Name--}}
<th>Staff</th> {{--Column Staff count, powered by withCount('staff') in the controller--}}
<th>Status</th> {{--Column Status--}} <th>Status</th> {{--Column Status--}}
<th>Actions</th> {{--Column Actions--}} <th>Actions</th> {{--Column Actions--}}
</tr> </tr>
...@@ -21,7 +22,11 @@ ...@@ -21,7 +22,11 @@
@forelse ($departments as $department) {{--This loops through the $departments collection that your controller in DepartmentController in index method passed to the view.--}} @forelse ($departments as $department) {{--This loops through the $departments collection that your controller in DepartmentController in index method passed to the view.--}}
<tr> <tr>
<td>{{ $department->code }}</td> {{--print the row's code column--}} <td>{{ $department->code }}</td> {{--print the row's code column--}}
<td>{{ $department->name }}</td> {{--print the row's code column--}} <td>{{ $department->name }}</td> {{--print the row's name column--}}
{{-- staff_count is a virtual column added by withCount('staff') in the controller.
Laravel names it automatically: the relationship name + _count.
This runs a single COUNT query for all departments, not one per row. --}}
<td>{{ $department->staff_count }}</td>
<td> {{--Is is_active true? If yes, use success. If no, use secondary. Inthis case secondary is "inactive"--}} <td> {{--Is is_active true? If yes, use success. If no, use secondary. Inthis case secondary is "inactive"--}}
<span class="badge bg-{{ $department->is_active ? 'success' : 'secondary' }}"> {{--In Bootstrap 5, bg-success is green and bg-secondary is grey.--}} <span class="badge bg-{{ $department->is_active ? 'success' : 'secondary' }}"> {{--In Bootstrap 5, bg-success is green and bg-secondary is grey.--}}
{{ $department->is_active ? 'Active' : 'Inactive' }} {{ $department->is_active ? 'Active' : 'Inactive' }}
...@@ -43,8 +48,9 @@ ...@@ -43,8 +48,9 @@
</td> </td>
</tr> </tr>
@empty @empty
{{-- Updated colspan from 4 to 5 because we added the Staff column --}}
<tr> <tr>
<td colspan="4" class="text-center">No departments found.</td> {{--This only runs if $departments has zero records.--}} <td colspan="5" class="text-center">No departments found.</td> {{--This only runs if $departments has zero records.--}}
</tr> </tr>
@endforelse @endforelse
</tbody> </tbody>
......
...@@ -28,9 +28,55 @@ ...@@ -28,9 +28,55 @@
</tr> </tr>
</table> </table>
{{-- Staff listing for this department.
$department->staff was already loaded and sorted by name in the controller
using load(), so accessing it here does NOT run another database query.
This is the "eager loading" technique from the training slides.
count() on the loaded collection also runs no extra query because
the data is already sitting in memory. --}}
<h3 class="mt-4">Staff ({{ $department->staff->count() }})</h3>
{{-- table-striped gives alternating row colours so the list is easier to read --}}
<table class="table table-striped">
<thead>
<tr>
<th>Staff No</th>
<th>Name</th>
<th>Email</th>
<th>Position</th>
<th>Join Date</th>
</tr>
</thead>
<tbody>
{{-- @forelse works like @foreach but has an @empty block
that shows when the collection has zero items.
This way the page never shows a broken empty table.
If a department has no staff yet, the user sees a
friendly message instead of blank space. --}}
@forelse ($department->staff as $staff)
<tr>
<td>{{ $staff->staff_no }}</td>
<td>{{ $staff->name }}</td>
<td>{{ $staff->email }}</td>
<td>{{ $staff->position }}</td>
{{-- join_date is stored as a date column in MySQL.
Laravel returns it as-is here (e.g. 2024-06-15).
In Week 7 you could format it with Carbon if needed. --}}
<td>{{ $staff->join_date }}</td>
</tr>
@empty
{{-- colspan="5" stretches this single cell across all 5 columns
so the message sits neatly inside the table --}}
<tr>
<td colspan="5">No staff in this department yet.</td>
</tr>
@endforelse
</tbody>
</table>
{{--Two navigation options. "Back to List" returns to /departments. {{--Two navigation options. "Back to List" returns to /departments.
"Edit" takes the user straight to the edit form for this specific "Edit" takes the user straight to the edit form for this specific
department, building a URL like /departments/5/edit.--}} department, building a URL like /departments/5/edit.--}}
<a href="{{ route('departments.index') }}" class="btn btn-secondary">Back to List</a> <a href="{{ route('departments.index') }}" class="btn btn-secondary">Back to List</a>
<a href="{{ route('departments.edit', $department) }}" class="btn btn-warning">Edit</a> {{--"Edit" goes to departments.edit, which is /departments/{department}/edit. It needs to know which department to edit, so you pass $department and Laravel pulls the ID from it to build a URL like /departments/5/edit.--}} <a href="{{ route('departments.edit', $department) }}" class="btn btn-warning">Edit</a>
@endsection @endsection
\ No newline at end of file
...@@ -2,6 +2,14 @@ ...@@ -2,6 +2,14 @@
<div class="alert alert-success">{{ session('success') }}</div> <div class="alert alert-success">{{ session('success') }}</div>
@endif @endif
{{-- Shows a red alert when something went wrong, like trying to
delete a department that still has staff. The controller sends
this with ->with('error', 'Move or remove its staff first.').
alert-danger is Bootstrap's red alert style. --}}
@if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif
{{--This file uses the structure in components/alert.blade.php--}} {{--This file uses the structure in components/alert.blade.php--}}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment