Commit c0855985 by Amshar

WEEK 8 - FILE UPLOADS & STORAGE

parent 2019b9cf
......@@ -7,6 +7,7 @@
use App\Models\Staff;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class StaffController extends Controller
{
......@@ -100,28 +101,62 @@ public function create()
/**
* Save a new staff member to the database.
*
* Notice we type-hint StoreStaffRequest instead of the usual Request.
* Notice the type-hint StoreStaffRequest instead of the usual Request.
* This tells Laravel to run our validation rules BEFORE this method
* even executes. If validation fails, the user is sent back to the
* form automatically — this code never runs.
*
* validated() returns only the fields that passed the rules,
* so nothing unexpected can sneak into the database.
* so nothing unexpected can sneak into the database. But we need
* to handle the photo separately because the form sends a FILE
* object, not a string. We store the file on disk and save only
* the PATH to the database.
*/
public function store(StoreStaffRequest $request)
{
Staff::create($request->validated());
// Get all validated fields EXCEPT the photo file object.
// We handle the photo and file with the datas separately below because we need to
// save to storage/app/public/staff-photos/ (the public disk, accessible by URL) for photos.
// to storage/app/private/staff-contracts/ (the local/private disk, no URL, only downloadable through a controller route) for pdf files.
$data = $request->safe()->except(['photo', 'contract']);
// If the user picked a photo, save it to the staff-photos
// folder on the public disk. store() generates a random
// filename like "x7f3aBc9.jpg" to avoid name collisions
// (two people both uploading "photo.jpg" won't overwrite
// each other). It returns the path relative to the disk,
// e.g. "staff-photos/x7f3aBc9.jpg" — that's what we save
// in the database.
if ($request->hasFile('photo')) {
$data['photo_path'] = $request->file('photo')
->store('staff-photos', 'public');
}
// If a contract PDF was uploaded, store it on the LOCAL (private) disk.
// Notice we don't pass 'public' as the second argument — that means
// Laravel uses the default 'local' disk, which saves to
// storage/app/private/. These files have no public URL.
if ($request->hasFile('contract')) {
$data['contract_path'] = $request->file('contract')
->store('staff-contracts');
}
Staff::create($data);
return redirect()->route('staff.index')
->with('success', 'Staff member added.');
}
/**
* Display the specified resource.
* Display a single staff member's profile.
*
* Route model binding automatically finds the staff record
* by ID from the URL (e.g. /staff/7 loads Staff #7).
* If the ID doesn't exist, Laravel returns a 404.
*/
public function show(Staff $staff)
{
//
return view('staff.show', compact('staff'));
}
/**
......@@ -140,13 +175,46 @@ public function edit(Staff $staff)
/**
* Update an existing staff member.
*
* Same idea as store(), but with UpdateStaffRequest which
* uses Rule::unique()->ignore() so the staff member can keep
* their own staff_no and email without triggering "already taken."
* Same idea as store(), but with one extra step: if the user uploads
* a NEW photo, we delete the OLD file from disk first. Without this,
* every time someone changes their photo, the old file stays in
* storage/app/public/staff-photos/ forever, wasting disk space.
* These leftover files are called "orphans."
*/
public function update(UpdateStaffRequest $request, Staff $staff)
{
$staff->update($request->validated());
// Get all validated fields except the photo and contract file objects,
// same as store(). We handle files separately below.
$data = $request->safe()->except(['photo', 'contract']);
// If the user picked a new photo...
if ($request->hasFile('photo')) {
// ...delete the old one first (if there was one).
// We check because the staff member might not have had
// a photo before, and calling delete() on a null path
// would be pointless.
if ($staff->photo_path) {
Storage::disk('public')->delete($staff->photo_path);
}
// Store the new photo and save its path.
$data['photo_path'] = $request->file('photo')
->store('staff-photos', 'public');
}
// Same pattern as photo: delete the old contract before saving the new one.
if ($request->hasFile('contract')) {
if ($staff->contract_path) {
Storage::delete($staff->contract_path);
}
$data['contract_path'] = $request->file('contract')
->store('staff-contracts');
}
// If no new file was picked, $data has no 'photo_path' key,
// so the existing photo stays untouched in the database.
$staff->update($data);
return redirect()->route('staff.index')
->with('success', 'Staff updated.');
......@@ -155,13 +223,46 @@ public function update(UpdateStaffRequest $request, Staff $staff)
/**
* Delete a staff member.
*
* We delete the photo file FIRST, then the database record.
* If we did it the other way around, we'd lose the photo_path
* value and have no way to know which file to delete — it would
* become an orphan sitting in storage forever.
*
* back() sends the user to whatever page they were on (the staff list),
* so they stay on the same pagination page instead of jumping to page 1.
*/
public function destroy(Staff $staff)
{
// Remove the photo file from disk if one exists.
if ($staff->photo_path) {
Storage::disk('public')->delete($staff->photo_path);
}
// Remove the contract file from the private disk if one exists.
if ($staff->contract_path) {
Storage::delete($staff->contract_path);
}
$staff->delete();
return back()->with('success', 'Staff member deleted.');
}
/**
* Download the staff member's contract PDF.
*
* This is the only way to access private files. The route is
* inside the auth group, so guests can't reach it. Storage::download()
* reads the file from the private disk and streams it to the browser
* as a download — no public URL is ever created.
*/
public function downloadContract(Staff $staff)
{
// If there's no contract, show a 404 instead of an error
if (! $staff->contract_path) {
abort(404);
}
return Storage::download($staff->contract_path); // It returns a download response. Instead of showing a web page, the browser gets the file streamed to it and opens a “Save as” dialog (or downloads it automatically, depending on browser settings).
}
}
......@@ -34,6 +34,8 @@ public function rules(): array
'department_id' => 'required|exists:departments,id',
'position' => 'required|max:100',
'join_date' => 'required|date|before_or_equal:today',
'photo' => 'nullable|image|mimes:jpg,png,webp|max:2048', // 2MB
'contract' => 'nullable|file|mimes:pdf|max:5120', // 5MB
];
}
......
......@@ -57,6 +57,7 @@ public function rules(): array
'department_id' => 'required|exists:departments,id',
'position' => 'required|max:100',
'join_date' => 'required|date|before_or_equal:today',
'photo' => 'nullable|image|mimes:jpg,png,webp|max:2048',
];
}
......
......@@ -5,6 +5,8 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Storage;
class Staff extends Model
{
......@@ -19,6 +21,8 @@ class Staff extends Model
'staff_no',
'name',
'email',
'photo_path',
'contract_path',
'position',
'join_date',
];
......@@ -42,4 +46,44 @@ public function department(): BelongsTo
{
return $this->belongsTo(Department::class);
}
/**
* Accessor: $staff->photo_url
*
* Instead of writing Storage::url($staff->photo_path) everywhere
* in the views, we create an accessor so we can just use
* $staff->photo_url. Laravel sees the method name "photoUrl"
* and lets you access it as $staff->photo_url (snake_case).
*
* Returns null if there's no photo, so the view can fall back
* to showing initials instead.
*/
protected function photoUrl(): Attribute
{
return Attribute::get(fn () => $this->photo_path
? Storage::url($this->photo_path)
: null);
}
/**
* Accessor: $staff->initials
*
* When a staff member has no photo, we show their initials
* as a fallback (like how Gmail shows "AR" for Aina Rahman
* when there's no profile picture).
*
* How it works:
* 1. Split the name by spaces: "Aina Rahman" → ["Aina", "Rahman"]
* 2. Take the first two words (in case someone has a long name)
* 3. Grab the first letter of each and capitalise it
* 4. Join them together: "AR"
*/
protected function initials(): Attribute
{
return Attribute::get(fn () => collect(
explode(' ', $this->name))
->take(2)
->map(fn ($word) => strtoupper($word[0]))
->join(''));
}
}
\ 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
{
/**
* We're adding a column to store the FILE PATH of the staff member's photo at staff table.
*
* Why a path and not the actual image?
* Storing binary files in MySQL makes the database huge and slow to back up.
* A short string like "staff-photos/x7f3a.jpg" keeps the row tiny,
* and the actual file lives on disk where it belongs.
*
* nullable() because a photo is optional — not every staff member will have one.
* after('email') puts it in a logical spot in the table, right after the email column.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('photo_path')->nullable()->after('email');
});
}
/**
* Undo the change: drop the column if we roll back.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->dropColumn('photo_path');
});
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* A nullable column to store the file path of the staff member's
* PDF contract. Unlike photo_path which uses the public disk,
* this path points to a file on the private local disk
* (storage/app/private/) so it can never be accessed by URL.
* Only a controller route behind auth can serve it.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('contract_path')->nullable()->after('photo_path');
});
}
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->dropColumn('contract_path');
});
}
};
......@@ -193,4 +193,93 @@
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
{{--
Photo Upload
type="file" shows a file picker button in the browser.
The name="photo" matches the 'photo' rule in the Form Request.
accept="image/jpeg,image/png,image/webp" tells the file picker
to only show these image types by default. But the user can
still switch to "all files" and pick anything, which is why
we validate on the server too with the 'image' and 'mimes' rules.
The small text below tells the user the limits BEFORE they try
to upload, so they don't waste time picking a 10 MB BMP file.
--}}
<div class="col-md-6">
<label for="photo" class="form-label">Photo</label>
<input
type="file"
name="photo"
id="photo"
class="form-control @error('photo') is-invalid @enderror"
accept="image/jpeg,image/png,image/webp"
>
<small class="text-muted">JPG, PNG or WEBP, up to 2 MB</small>
@error('photo')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
{{--
On the edit page, if the staff member already has a photo,
show a small preview so they know what's currently saved.
They only need to pick a new file if they want to replace it.
--}}
@if (isset($staff) && $staff->photo_path)
<div class="mt-2">
<img
src="{{ Storage::url($staff->photo_path) }}"
alt="{{ $staff->name }}"
width="80"
height="80"
class="rounded"
>
<small class="text-muted d-block">Current photo</small>
</div>
@endif
</div>
</div>
<div class="row mb-3">
{{--
Contract Upload (Private)
Unlike the photo which goes on the public disk (anyone with
the URL can see it), the contract goes on the private local
disk (storage/app/private/). There's no URL to access it
directly — only a controller route behind auth middleware
can serve the file using Storage::download().
This is how you handle sensitive documents like contracts,
ID scans or payslips that shouldn't be publicly accessible.
--}}
<div class="col-md-6">
<label for="contract" class="form-label">Contract (PDF)</label>
<input
type="file"
name="contract"
id="contract"
class="form-control @error('contract') is-invalid @enderror"
accept="application/pdf"
>
<small class="text-muted">PDF only, up to 5 MB</small>
@error('contract')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
{{--
On the edit page, if the staff member already has a contract,
show a link so they know one exists. The download route
is behind auth, so only signed-in users can access it.
--}}
@if (isset($staff) && $staff->contract_path)
<div class="mt-2">
<small class="text-muted">
<a href="{{ route('staff.contract', $staff) }}">Download current contract</a>
</small>
</div>
@endif
</div>
</div>
\ No newline at end of file
......@@ -24,7 +24,7 @@
The edit form uses @method('PUT') instead, but create
just needs a plain POST.
--}}
<form method="POST" action="{{ route('staff.store') }}">
<form method="POST" action="{{ route('staff.store') }}" enctype="multipart/form-data">
{{--
@csrf adds a hidden token field to the form.
It proves this form was submitted from our own site,
......
......@@ -25,7 +25,7 @@
using the staff member's ID. Laravel's route model binding
then finds Staff::findOrFail(7) automatically.
--}}
<form method="POST" action="{{ route('staff.update', $staff) }}">
<form method="POST" action="{{ route('staff.update', $staff) }}" enctype="multipart/form-data">
{{--
@csrf is the same security token as the create form.
Every form needs it, whether creating or editing.
......
......@@ -85,6 +85,7 @@
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>Staff No</th>
<th>Name</th>
<th>Email</th>
......@@ -102,6 +103,31 @@
--}}
@forelse ($staff as $s)
<tr>
<td>
{{--
Show the staff photo if they have one,
otherwise show their initials in a coloured circle.
This keeps every row the same height and gives
a visual identity even without a photo.
--}}
@if ($s->photo_url)
<img
src="{{ $s->photo_url }}"
alt="{{ $s->name }}"
width="40"
height="40"
class="rounded-circle"
style="object-fit: cover;"
>
@else
<span
class="d-inline-flex align-items-center justify-content-center rounded-circle text-white fw-bold"
style="width: 40px; height: 40px; background-color: #6c757d; font-size: 14px;"
>
{{ $s->initials }}
</span>
@endif
</td>
<td>{{ $s->staff_no }}</td>
<td>{{ $s->name }}</td>
<td>{{ $s->email }}</td>
......@@ -136,7 +162,7 @@
@empty
{{-- Shown when no staff match the search or filter --}}
<tr>
<td colspan="7" class="text-center text-muted py-4">
<td colspan="8" class="text-center text-muted py-4">
No staff found.
</td>
</tr>
......
{{--
Staff profile page.
Shows a single staff member's details with their photo
(or initials if they don't have one). This is a read-only
view — editing happens on the edit page.
--}}
@extends('layouts.app')
{{-- Use the staff member's name as the page title in the browser tab --}}
@section('title', $staff->name)
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>{{ $staff->name }}</h1>
<div>
{{--
Edit links to the edit form for this specific staff member.
route('staff.edit', $staff) generates a URL like /staff/7/edit
using the staff member's ID.
--}}
<a href="{{ route('staff.edit', $staff) }}" class="btn btn-primary">Edit</a>
<a href="{{ route('staff.index') }}" class="btn btn-secondary">Back to list</a>
</div>
</div>
<div class="row">
{{--
Photo or initials fallback.
The layout puts the photo in a narrow column (col-md-3, about 25%
of the width) and the details table in the wider column (col-md-9,
about 75%). This mirrors a typical profile page layout.
--}}
<div class="col-md-3 text-center mb-3">
@if ($staff->photo_url)
{{--
$staff->photo_url is the accessor we built in the model.
It converts the raw database path (staff-photos/x7f3a.jpg)
into a browser-friendly URL (/storage/staff-photos/x7f3a.jpg).
object-fit: cover crops the image to fill the circle evenly,
so a tall portrait or wide landscape won't stretch or squash.
Always set alt text for accessibility — screen readers read
it aloud for visually impaired users.
--}}
<img
src="{{ $staff->photo_url }}"
alt="{{ $staff->name }}"
width="150"
height="150"
class="rounded-circle"
style="object-fit: cover;"
>
@else
{{--
No photo? Show initials in a grey circle instead.
This is the same pattern as the index page, just bigger
(150px instead of 40px) since this is a profile page.
$staff->initials is another accessor — it takes
"Aina Rahman" and returns "AR".
--}}
<span
class="d-inline-flex align-items-center justify-content-center rounded-circle text-white fw-bold"
style="width: 150px; height: 150px; background-color: #6c757d; font-size: 48px;"
>
{{ $staff->initials }}
</span>
@endif
</div>
{{--
Staff details in a simple table.
We use a vertical table (labels on the left, values on the right)
instead of a horizontal one because it reads more naturally for
a single record. The index page uses a horizontal table because
it shows many records in rows.
$staff->department->name works without an extra query because
Laravel eager-loads the relationship. If you see an N+1 warning
in Debugbar, add ->load('department') in the controller's show().
--}}
<div class="col-md-9">
<table class="table">
<tr>
<th style="width: 200px;">Staff No</th>
<td>{{ $staff->staff_no }}</td>
</tr>
<tr>
<th>Name</th>
<td>{{ $staff->name }}</td>
</tr>
<tr>
<th>Email</th>
<td>{{ $staff->email }}</td>
</tr>
<tr>
<th>Department</th>
<td>{{ $staff->department->name }}</td>
</tr>
<tr>
<th>Position</th>
<td>{{ $staff->position }}</td>
</tr>
<tr>
{{--
format('d M Y') turns the raw date 2026-10-01 into
"01 Oct 2026" which is easier to read. This works
because we cast join_date to a date in the model,
giving us a Carbon object with formatting methods.
--}}
<th>Join Date</th>
<td>{{ $staff->join_date->format('d M Y') }}</td>
</tr>
</table>
</div>
</div>
@endsection
\ No newline at end of file
......@@ -51,6 +51,33 @@
Route::resource('departments', DepartmentController::class);
Route::resource('positions', PositionController::class);
Route::resource('staff', StaffController::class);
Route::get('/staff/{staff}/contract', [StaffController::class, 'downloadContract'])
->name('staff.contract');
/*
|--------------------------------------------------------------------------
| Custom Staff Route — Contract Download
|--------------------------------------------------------------------------
|
| Route::resource('staff', ...) only creates the standard seven CRUD
| routes (index, create, store, show, edit, update, destroy).
| Downloading a contract isn't one of those seven, so we define
| it manually as an extra route.Therefore, we have to create a new route
| instead of using Route::resource('staff', StaffController::class); as the route
|
| GET /staff/{staff}/contract triggers downloadContract() on the
| controller. {staff} is the staff member's ID — Laravel uses
| route model binding to find the record automatically.
|
| ->name('staff.contract') gives it a name so we can link to it
| in Blade with route('staff.contract', $staff) instead of
| hardcoding the URL.
|
| This route sits inside the auth group, so only signed-in users
| can reach it. That's what makes the contract "private" — there's
| no public URL, and the middleware acts as the bouncer.
|
*/
});
/* CHANGE FROM Route::middleware('auth')... to Route::middleware(['auth', 'active'])
......
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