Commit 2077fe62 by Amshar

WEEK 11 - DASHBOARD, REPORTS & EXPORT

parent eae52eb4
<?php
namespace App\Http\Controllers;
use App\Models\Asset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* THIS FILE BASICALLY JUST SPECIALISE TO INSTRUCT THE PIVOT TABLE (LOGBOOK)
*/
class AssetAssignmentController extends Controller
{
/**
* Assign an asset to one staff member.
*
* This adds a NEW row to the asset_staff logbook with attach().
* We never use detach() or sync() for assignments, because they
* delete logbook rows and the history would be lost.
*/
public function store(Request $request, Asset $asset) // assigns an asset to a staff member. It runs when you pick someone in the “Assign to” dropdown and click Assign.
{
$data = $request->validate([
'staff_id' => 'required|exists:staff,id',
], [
'staff_id.required' => 'Please pick a staff member.',
'staff_id.exists' => 'Please pick a valid staff member.',
]);
// DB::transaction runs everything inside as one all-or-nothing unit.
// We use a normal function with use (...) instead of a one-line fn,
// because there are two writes (the logbook row and the status).
// The value we return from inside is what DB::transaction hands back.
$assigned = DB::transaction(function () use ($asset, $data) {
// Load the asset again and lock its row until we finish.
// Without the lock, a double click could run this twice at the
// same moment and hand the same laptop to two people.
$locked = Asset::lockForUpdate()->find($asset->id);
// Only an available asset can be handed out. One that is in use
// or in repair cannot be assigned twice.
if ($locked->status !== 'available') {
return false;
}
// Write 1: add a new logbook line. assigned_at is today,
// returned_at is left empty, which means "still with them".
$locked->staff()->attach($data['staff_id'], [
'assigned_at' => now()->toDateString(),
]);
// Write 2: mark the asset as in use.
$locked->update(['status' => 'in_use']);
return true;
});
if (! $assigned) {
return back()->with('error', 'This asset is not available to assign.');
}
return back()->with('success', 'Asset assigned.');
}
/**
* Return an asset.
*
* Nothing is deleted. We find the logbook line that has no return
* date yet and fill it in. The route verb is DELETE only because it
* is the standard resource shape. The data itself is kept.
*
* // Not deleting anything, destroy() returns an asset. It’s the
* asset that is being returned and In the logbook, that means updating
* the open row by filling in returned_at. It doesn’t fetch or return
* a row to anyone. Different from show() in AssetController where it
* only shows an asset to the user, it updates too at the logbook
* (asset_staff table)
*/
public function destroy(Asset $asset)
{
$returned = DB::transaction(function () use ($asset) {
// newPivotQuery() lets us run a plain update on this asset's
// logbook rows. whereNull('returned_at') picks the open line.
// A plain query skips withTimestamps(), so we set updated_at
// ourselves. update() returns how many rows changed.
$rows = $asset->staff()->newPivotQuery()
->whereNull('returned_at')
->update([
'returned_at' => now()->toDateString(),
'updated_at' => now(),
]);
// No open line means nobody was holding it, so there is nothing to return.
if ($rows === 0) {
return false;
}
// The asset is back in the cupboard and can be handed out again.
$asset->update(['status' => 'available']);
return true;
});
if (! $returned) {
return back()->with('error', 'This asset is not currently assigned.');
}
return back()->with('success', 'Asset returned.');
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreAssetRequest;
use App\Http\Requests\UpdateAssetRequest;
use App\Models\Asset;
use App\Models\Staff;
class AssetController extends Controller
{
/**
* Show the asset list, 10 per page, sorted by tag.
* Who may open this page is decided in routes/web.php
* (the view-assets Gate: Admin and Manager).
* Trashed assets are skipped automatically because of SoftDeletes.
*/
public function index()
{
/**
* the query now loads each asset’s current holder together with the assets,
* using with(['staff' => ...]). The wherePivotNull('returned_at') filter
* means it only brings back people who haven’t returned the item yet, so old
* holders from the history are left out. This query uses the n+1 concept
*/
$assets = Asset::with(['staff' => fn ($q) => $q->wherePivotNull('returned_at')])
->orderBy('asset_tag')
->paginate(10);
return view('assets.index', compact('assets'));
}
/**
* Show the empty "add asset" form.
*/
public function create()
{
return view('assets.create');
}
/**
* Save a new asset. StoreAssetRequest has already validated
* the form by the time this code runs.
*/
public function store(StoreAssetRequest $request)
{
Asset::create($request->validated());
return redirect()->route('assets.index')
->with('success', 'Asset added.');
}
/**
* Show one asset with its full holder history.
*
* orderByPivot() sorts by a column on the logbook table, so the
* newest handover appears first. The second sort breaks ties when
* two handovers happen on the same day.
*
* $staffList fills the "Assign to" dropdown. Only Admins can assign,
* so for everyone else we skip the query and send an empty collection.
*/
public function show(Asset $asset)
{
$asset->load(['staff' => fn ($q) => $q
->orderByPivot('assigned_at', 'desc')
->orderByPivot('id', 'desc')]);
$staffList = auth()->user()->isAdmin()
? Staff::orderBy('name')->get()
: collect();
return view('assets.show', compact('asset', 'staffList'));
}
/**
* Show the edit form, pre-filled with the asset's current values.
*/
public function edit(Asset $asset)
{
return view('assets.edit', compact('asset'));
}
/**
* Save changes to an existing asset.
*/
public function update(UpdateAssetRequest $request, Asset $asset)
{
$asset->update($request->validated());
return redirect()->route('assets.index')
->with('success', 'Asset updated.');
}
/**
* Move an asset to the trash.
*
* First we check that nobody is holding it right now, the same
* "check before MySQL complains" idea as DepartmentController.
* wherePivotNull('returned_at') finds logbook rows with no return date.
*
* delete() now only fills in deleted_at, because the Asset model uses
* SoftDeletes. The row and its logbook history stay in the database.
*/
public function destroy(Asset $asset)
{
if ($asset->staff()->wherePivotNull('returned_at')->exists()) {
return back()->with('error', 'Return this asset before deleting it.');
}
$asset->delete();
return back()->with('success', 'Asset moved to the trash.');
}
/**
* The Trash page: only the deleted assets, newest deletion first.
* onlyTrashed() flips the SoftDeletes rule, so we see ONLY the hidden rows.
*
* The Trash page is where deleted assets go to wait. Once soft deleting is
* on, an asset you delete disappears from the normal asset list, but it isn’t
* gone. The Trash page lists exactly those hidden assets, with the date each
* was deleted.
*
* Restore is the “undo” button on that page. It puts a trashed asset back in
* the normal list as if it had never been deleted. Its tag, details and full
* assignment history all come back with it.
*
* Without them, a soft-deleted asset would be hidden with no way to see it or
* get it back, except by editing the database by hand in SQLyog. So these two
* are what make deleting safe.
*
* If someone deletes an asset by mistake, the Admin opens Trash and clicks Restore.
*
*/
public function trash()
{
$assets = Asset::onlyTrashed()->latest('deleted_at')->paginate(10);
return view('assets.trash', compact('assets'));
}
/**
* Bring a trashed asset back.
* restore() clears deleted_at, so the asset shows up in the list again.
* The route needs ->withTrashed(), otherwise Laravel cannot find a
* trashed asset by its ID and returns a 404.
*/
public function restore(Asset $asset)
{
$asset->restore();
return back()->with('success', 'Asset restored.');
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers;
use App\Models\Asset;
use App\Models\Staff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
/**
* THIS IS BASICALLY THE FILE FOR THE CONTROLLER THAT HANDLES AssetStaff TABLE ON THE STAFF SIDE
* here is to help assignning assets to a staff on the staff side (but only admins can do this)
*/
class StaffAssetController extends Controller
{
/**
* Assign several assets to one staff member in one save.
*
* The staff page sends the ticked checkboxes as an array:
* asset_ids = [3, 5, 8]. Each one becomes a new logbook row with
* attach(). We never use sync() here, because sync() removes every
* logbook row that is not in the list and that destroys history.
*/
public function store(Request $request, Staff $staff)
{
$data = $request->validate([
// At least one box must be ticked, and the value must be an array.
'asset_ids' => 'required|array',
// Each ticked ID must exist, be available, and not be in the trash.
// This stops a tampered form from assigning an asset that is
// already in use, in repair, disposed or deleted.
'asset_ids.*' => [
Rule::exists('assets', 'id')
->where('status', 'available')
->whereNull('deleted_at'),
],
], [
'asset_ids.required' => 'Tick at least one asset to assign.',
'asset_ids.*.exists' => 'One of the ticked assets is no longer available.',
]);
// Remove any repeated IDs and make sure we have a clean list.
$ids = array_values(array_unique($data['asset_ids']));
// All-or-nothing: the logbook rows and the status changes
// succeed together or fail together. Normal function with use (...)
// because there is more than one write.
$assignedCount = DB::transaction(function () use ($staff, $ids) {
// Lock the ticked assets and check again that they are all still
// available. Someone else may have taken one a moment ago.
$stillAvailable = Asset::whereIn('id', $ids)
->where('status', 'available')
->lockForUpdate()
->pluck('id');
if ($stillAvailable->count() !== count($ids)) {
return null;
}
// Write 1: one new logbook row per asset, all with the same
// assigned_at date. returned_at stays empty.
$staff->assets()->attach($ids, [
'assigned_at' => now()->toDateString(),
]);
// Write 2: mark every ticked asset as in use.
Asset::whereIn('id', $ids)->update(['status' => 'in_use']);
return count($ids);
});
if ($assignedCount === null) {
return back()->with('error', 'Some of those assets were just taken. Please try again.');
}
return back()->with('success', $assignedCount . ' asset(s) assigned to ' . $staff->name . '.');
}
}
\ No newline at end of file
......@@ -4,9 +4,11 @@
use App\Http\Requests\StoreStaffRequest;
use App\Http\Requests\UpdateStaffRequest;
use App\Models\Asset;
use App\Models\Staff;
use App\Models\Department;
use App\Models\Position;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Gate;
......@@ -191,6 +193,15 @@ public function store(StoreStaffRequest $request)
* 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.
*
* Week 10: the page also shows this person's asset history.
* Two queries, one relation:
* - currentAssets: logbook rows with no returned_at (holding now)
* - pastAssets: logbook rows with a returned_at (already handed back)
* orderByPivot() sorts by a column on the logbook table.
*
* $availableAssets feeds the checkbox list. Only Admins can assign,
* so for everyone else we skip the query and send an empty collection.
*/
public function show(Staff $staff)
{
......@@ -198,7 +209,28 @@ public function show(Staff $staff)
// This is what stops a Manager typing /staff/42 from another department.
Gate::authorize('view', $staff);
return view('staff.show', compact('staff'));
/**
* HERE WE ARE USING THE ASSETS TABLE HERE
*
* The controller fetches the data, and the page just displays it.
*
* $currentAssets is what this person holds now. It feeds the Current assets table, newest first.
* $pastAssets is what they’ve handed back. It feeds the Past assets table, most recently returned first.
* $availableAssets is every asset with status available. It feeds the checkbox list. Only Admins can assign, so for everyone else we skip that query and send an empty list.
*/
$currentAssets = $staff->currentAssets()
->orderByPivot('assigned_at', 'desc')
->get();
$pastAssets = $staff->pastAssets()
->orderByPivot('returned_at', 'desc')
->get();
$availableAssets = auth()->user()->isAdmin()
? Asset::where('status', 'available')->orderBy('asset_tag')->get()
: collect();
return view('staff.show', compact('staff', 'currentAssets', 'pastAssets', 'availableAssets'));
}
/**
......@@ -275,10 +307,18 @@ 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.
* Week 10 change: the order is now reversed. We delete the DATABASE
* RECORD first, and only remove the photo and contract files after
* that worked. Before, the files were deleted first, so if MySQL
* refused to delete the record, the files were already gone but the
* staff member was still there.
*
* Why MySQL may refuse: the asset_staff logbook uses restrictOnDelete()
* on staff_id, and the users table links to staff too. A staff member
* who still has linked records cannot be deleted. MySQL throws a
* QueryException with the SQLSTATE code 23000 (integrity constraint).
* We catch exactly that code and show a friendly message. Any other
* database problem is thrown again, so real errors are not hidden.
*
* 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.
......@@ -287,6 +327,40 @@ public function destroy(Staff $staff)
{
Gate::authorize('delete', $staff);
/**
* The problem. Your asset_staff table was built with restrictOnDelete()
* on staff_id. That means MySQL refuses to delete a staff member who has
* logbook history, which is the whole point, because it protects the history.
* Without any handling, Laravel would show an ugly error page.
*
* First, we catch the error and show a friendly message: (look at code)
*
* - try means “attempt the delete”.
* - catch means “if the database refuses, run this instead of crashing”.
* - Code 23000 is MySQL’s code for “this breaks a link between tables”.
* We only handle that one. Any other database problem is thrown again,
* so real bugs are not hidden.
*
* Second, we changed the order. Before, the code deleted the photo and
* contract files first and the database record second. If MySQL then refused,
* the staff member was still there but their photo and contract were
* already gone. Now the record is deleted first, and the files are removed
* only after that succeeded. If the delete is refused, the code returns
* early and the files are left alone. (If you lok at the code, we delete the
* staff first, then photo, then file)
*/
try {
$staff->delete();
} catch (QueryException $e) {
if ((string) $e->getCode() === '23000') {
return back()->with('error', 'This staff member cannot be deleted because other records still depend on them, such as asset history. History is kept on purpose.');
}
throw $e;
}
// The record is gone, so it is now safe to remove the files.
// Remove the photo file from disk if one exists.
if ($staff->photo_path) {
Storage::disk('public')->delete($staff->photo_path);
......@@ -297,8 +371,6 @@ public function destroy(Staff $staff)
Storage::delete($staff->contract_path);
}
$staff->delete();
return back()->with('success', 'Staff member deleted.');
}
......@@ -324,4 +396,4 @@ public function downloadContract(Staff $staff)
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).
}
}
}
\ No newline at end of file
<?php
namespace App\Http\Requests;
use App\Models\Asset;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreAssetRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request. Only Admins add assets.
* Only Admins add assets. The route is already behind role:admin, so this is a
* second lock.
*/
public function authorize(): bool
{
return $this->user()?->isAdmin() ?? false; // If a user is logged in, $this->user() returns the User object, and PHP calls ->isAdmin() on it. If no user is logged in (a guest), $this->user() returns null. • The ?? operator checks the value on its left: if it is null, it falls back to the value on its right (false).
}
/**
* Validation rules for adding a new asset.
* If any rule fails, Laravel sends the user back to the form
* with error messages and the old input.
*/
public function rules(): array
{
return [
'asset_tag' => 'required|max:20|unique:assets',
'name' => 'required|max:100',
'category' => 'required|max:50',
'purchase_date' => 'required|date|before_or_equal:today',
// Only the four allowed statuses, taken from the model's list.
'status' => ['required', Rule::in(array_keys(Asset::STATUSES))],
];
}
/**
* Friendlier wording for the rules most likely to trip people up.
*/
public function messages(): array
{
return [
'asset_tag.unique' => 'This asset tag is already taken.',
'purchase_date.before_or_equal' => 'The purchase date cannot be in the future.',
'status.in' => 'Please pick a valid status.',
];
}
}
<?php
namespace App\Http\Requests;
use App\Models\Asset;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateAssetRequest extends FormRequest
{
/**
* Only Admins edit assets (second lock behind the route middleware).
*/
public function authorize(): bool
{
return $this->user()?->isAdmin() ?? false;
}
/**
* Same rules as adding, except the unique check ignores THIS asset.
* Without ignore(), saving an asset with its own existing tag
* would fail because the tag "already exists" on the same row.
*/
public function rules(): array
{
return [
'asset_tag' => ['required', 'max:20', Rule::unique('assets')->ignore($this->route('asset'))],
'name' => 'required|max:100',
'category' => 'required|max:50',
'purchase_date' => 'required|date|before_or_equal:today',
// Only the four allowed statuses, taken from the model's list.
'status' => ['required', Rule::in(array_keys(Asset::STATUSES))],
];
}
public function messages(): array
{
return [
'asset_tag.unique' => 'This asset tag is already taken.',
'purchase_date.before_or_equal' => 'The purchase date cannot be in the future.',
'status.in' => 'Please pick a valid status.',
];
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
// Only these fields can be mass-assigned with create() or update().
// Same job as $fillable, written as an attribute like your User model.
#[Fillable(['asset_tag', 'name', 'category', 'purchase_date', 'status'])] // you can also write protected fillable
class Asset extends Model
{
/** @use HasFactory<\Database\Factories\AssetFactory> */
use HasFactory, SoftDeletes;
/**
* The only statuses an asset can have.
* The key is what we store in the database, the value is the
* friendly text we show on screen. One list, used by the form
* dropdown, the validation rule and the badge label.
*/
public const STATUSES = [
'available' => 'Available',
'in_use' => 'In use',
'repair' => 'Repair',
'disposed' => 'Disposed',
];
/**
* Turn purchase_date into a Carbon date object so we can call
* ->format('d M Y') on it, the same idea as join_date on Staff.
* “whenever you read purchase_date, turn it into a proper date object first.”
* With 'purchase_date' => 'date', Laravel converts the value
* into a Carbon object. Carbon is a date helper class that comes
* with Laravel, and it has methods that plain text doesn’t.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'purchase_date' => 'date',
];
}
/**
* Every staff member who has ever held this asset, past and present.
*
* belongsToMany goes through the asset_staff logbook table.
* Laravel finds that table name by itself: both model names in
* singular form, in alphabetical order.
*
* withPivot() lets us read the extra logbook columns through
* $staff->pivot->assigned_at and $staff->pivot->returned_at.
* withTimestamps() fills created_at and updated_at on the logbook row.
*/
public function staff(): BelongsToMany
{
return $this->belongsToMany(Staff::class)
->withPivot('assigned_at', 'returned_at') // By default, Laravel only reads the two ID columns from the logbook, asset_id and staff_id. They are what link the two sides together. The date columns are ignored, as if they weren’t on the form. withPivot tells Laravel to also read those two columns, and to put them on a small pivot object attached to each result:
->withTimestamps(); // So basically the timestams helps laravel to automactically write created_at and updated_at since both pf this columns are automatically written by larave. The only column we can fill are assigned_at and returned_at
}
/**
* The Bootstrap colour name for this asset's status.
* Used in Blade as: class="badge text-bg-{{ $asset->badge() }}"
* Keeping it here means every page shows the same colour
* for the same status.
*/
public function badge(): string
{
return match ($this->status) {
'available' => 'success',
'in_use' => 'primary',
'repair' => 'warning',
'disposed' => 'secondary',
default => 'dark',
};
}
/**
* The friendly text for this asset's status, like "In use".
* Falls back to the raw value if the status is ever unknown.
*
* How It Works Step-by-Step
* 1. self::STATUSES[$this->status]: It looks inside a constant array named STATUSES (defined on the same class) using $this->status as the key—for example, ['pending' => 'Pending Approval', 'paid' => 'Paid in Full'].
* 2. ?? (Null Coalescing Operator):
* • If the key exists in STATUSES (and isn't null), it returns that friendly label (e.g., 'Pending Approval').
* • If the key does NOT exist (or is null), it prevents an "Undefined array key" warning and safely falls back to returning the raw $this->status value on the right.
*/
public function statusLabel(): string
{
return self::STATUSES[$this->status] ?? $this->status;
}
}
......@@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Storage;
......@@ -55,6 +56,55 @@ public function position(): BelongsTo // This one position can have many staff.
}
/**
* WHY DO WE HAVE currentAssets() and pastAssets() AND NOT JUST assets()
* You could use assets() alone, but it returns the whole logbook
* for that person, past and present mixed together. Your staff page
* needs two separate tables, Current and Past, so something has to
* split them.
*
* $staff->assets // every asset ever held (returned or not)
* $staff->currentAssets // only rows where returned_at is empty
* $staff->pastAssets // only rows where returned_at is filled
*/
/**
* Every asset this staff member has ever held, past and present.
*
* This is the other half of Asset::staff(). Many-to-many must be
* written on BOTH models so we can start from either side.
* Laravel finds the asset_staff table by itself, and withPivot()
* lets us read assigned_at and returned_at from the logbook row.
*/
public function assets(): BelongsToMany
{
return $this->belongsToMany(Asset::class)
->withPivot('assigned_at', 'returned_at')
->withTimestamps();
}
/**
* Only the assets this person holds right now.
*
* An empty returned_at means "not handed back yet", so
* wherePivotNull('returned_at') keeps just those logbook rows.
* Use it as $staff->currentAssets (property) or
* $staff->currentAssets() (query builder).
*/
public function currentAssets(): BelongsToMany
{
return $this->assets()->wherePivotNull('returned_at');
}
/**
* Only the assets this person has already returned (their history).
* wherePivotNotNull is the opposite of wherePivotNull.
*/
public function pastAssets(): BelongsToMany
{
return $this->assets()->wherePivotNotNull('returned_at'); // wherePivotNotNull is the opposite of wherePivotNull.
}
/**
* Accessor: $staff->photo_url
*
* Instead of writing Storage::url($staff->photo_path) everywhere
......
<?php
namespace Database\Factories;
use App\Models\Asset;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Asset>
*/
class AssetFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
//
];
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations: build the assets table
*/
public function up(): void
{
Schema::create('assets', function (Blueprint $table) {
// Primary key, auto-incrementing
$table->id();
// The sticker on the laptop, like LPT-0042. Unique so no two
// assets can share one tag.
$table->string('asset_tag', 20)->unique();
// What the item is called, like "Dell Latitude 5440"
$table->string('name', 100);
// Laptop, printer, monitor and so on
$table->string('category', 50);
// A calendar date only, no time needed
$table->date('purchase_date');
// One of: available, in_use, repair, disposed.
// New assets start as 'available' unless we say otherwise.
$table->string('status', 20)->default('available');
// created_at and updated_at, managed by Laravel automatically
$table->timestamps();
// Adds a nullable deleted_at column. This is what makes
// soft deletes possible: instead of removing the row, Laravel
// fills in deleted_at with the date and hides the row.
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('assets');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migration: build the asset_staff logbook table.
*
* Each row is one handover: this asset, this person, taken on
* this date, returned on this date (or still empty if not returned).
*/
public function up(): void
{
Schema::create('asset_staff', function (Blueprint $table) {
$table->id();
// Which asset. cascadeOnDelete() (hard deleting) means that if an asset row is
// ever permanently removed, its logbook lines go with it.
// (Soft deleting only hides the asset, so history stays.)
$table->foreignId('asset_id')
->constrained()
->cascadeOnDelete();
// Which staff member. 'staff' is passed explicitly because the
// table name is singular, so Laravel can't guess it from "staff_id".
// restrictOnDelete() blocks deleting a staff member who still
// has logbook history, so the history is never lost.
$table->foreignId('staff_id')
->constrained('staff')
->restrictOnDelete();
// The day the asset was handed out
$table->date('assigned_at');
// The day it came back. Nullable: empty means "still with them".
$table->date('returned_at')->nullable();
// created_at and updated_at for the logbook row itself
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('asset_staff');
}
};
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class AssetSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
//
}
}
{{--
Shared form fields for asset create and edit.
Both pages @include this file, so the fields only exist in one place.
If you ever need to add a field, you change it here and both forms update.
The $asset variable may or may not exist:
- Create page: $asset is not set, so old() has no fallback
- Edit page: $asset is passed in, so old() falls back to the saved value
--}}
<div class="row mb-3">
{{--
Asset Tag
maxlength="20" matches the max:20 rule in the Form Request.
The server still validates it, because the browser limit
can be bypassed with DevTools.
--}}
<div class="col-md-6">
<label for="asset_tag" class="form-label">Asset Tag</label>
<input
type="text"
name="asset_tag"
id="asset_tag"
class="form-control @error('asset_tag') is-invalid @enderror"
value="{{ old('asset_tag', $asset->asset_tag ?? '') }}"
maxlength="20"
>
@error('asset_tag')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
{{-- Name --}}
<div class="col-md-6">
<label for="name" class="form-label">Name</label>
<input
type="text"
name="name"
id="name"
class="form-control @error('name') is-invalid @enderror"
value="{{ old('name', $asset->name ?? '') }}"
maxlength="100"
>
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
{{-- Category: free text like Laptop, Printer or Monitor --}}
<div class="col-md-6">
<label for="category" class="form-label">Category</label>
<input
type="text"
name="category"
id="category"
class="form-control @error('category') is-invalid @enderror"
value="{{ old('category', $asset->category ?? '') }}"
maxlength="50"
>
@error('category')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
{{--
Purchase Date
type="date" needs the value as Y-m-d (a browser rule), so on edit
we use $asset->purchase_date->format('Y-m-d'). isset($asset) checks
that we are on the edit page first, because calling ->format()
on null would crash.
--}}
<div class="col-md-6">
<label for="purchase_date" class="form-label">Purchase Date</label>
<input
type="date"
name="purchase_date"
id="purchase_date"
class="form-control @error('purchase_date') is-invalid @enderror"
value="{{ old('purchase_date', isset($asset) ? $asset->purchase_date->format('Y-m-d') : '') }}"
>
@error('purchase_date')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
{{--
Status Dropdown
The options come from Asset::STATUSES, the same list the Form
Request uses to validate. The value sent to the server is the
key (like in_use), and the label (like "In use") is what the
user sees. On the create page, 'available' is pre-selected.
--}}
<div class="col-md-6">
<label for="status" class="form-label">Status</label>
<select
name="status"
id="status"
class="form-select @error('status') is-invalid @enderror"
>
@foreach (\App\Models\Asset::STATUSES as $value => $label)
<option
value="{{ $value }}"
@selected(old('status', $asset->status ?? 'available') === $value)
>
{{ $label }}
</option>
@endforeach
</select>
@error('status')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Add Asset')
@section('content')
<h1 class="mb-3">Add Asset</h1>
<form method="POST" action="{{ route('assets.store') }}">
@csrf
{{-- No $asset is passed, so the shared fields start empty --}}
@include('assets._form')
<button type="submit" class="btn btn-primary">Save</button>
<a href="{{ route('assets.index') }}" class="btn btn-secondary">Cancel</a>
</form>
@endsection
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Edit Asset')
@section('content')
<h1 class="mb-3">Edit Asset</h1>
<form method="POST" action="{{ route('assets.update', $asset) }}">
@csrf
{{-- HTML forms can only send GET or POST, so this hidden field tells Laravel it is an update --}}
@method('PUT')
{{-- $asset already exists on this page, so the shared fields fill in with its saved values --}}
@include('assets._form')
<button type="submit" class="btn btn-primary">Update</button>
<a href="{{ route('assets.index') }}" class="btn btn-secondary">Cancel</a>
</form>
@endsection
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Assets')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Assets</h1>
{{-- Only Admins may add assets or open the Trash, so Managers never see these buttons. --}}
@if (auth()->user()->isAdmin())
<div>
<a href="{{ route('assets.trash') }}" class="btn btn-outline-secondary">Trash</a>
<a href="{{ route('assets.create') }}" class="btn btn-primary">+ Add Asset</a>
</div>
@endif
</div>
<table class="table table-bordered table-hover">
<thead class="table-dark">
<tr>
<th>Tag</th>
<th>Name</th>
<th>Category</th>
<th>Purchased</th>
<th>Status</th>
<th>Held by</th> {{--added for coding challenge--}}
<th>Actions</th>
</tr>
</thead>
<tbody>
@forelse ($assets as $asset)
<tr>
<td>{{ $asset->asset_tag }}</td>
<td>{{ $asset->name }}</td>
<td>{{ $asset->category }}</td>
{{-- purchase_date is cast to a Carbon date in the model, so format() works --}}
<td>{{ $asset->purchase_date->format('d M Y') }}</td>
<td>
{{--
badge() in the Asset model returns the Bootstrap colour name,
so text-bg-success, text-bg-primary and so on.
statusLabel() returns the friendly text, like "In use".
--}}
<span class="badge text-bg-{{ $asset->badge() }}">{{ $asset->statusLabel() }}</span>
</td>
<td>
{{-- staff was eager loaded with only unreturned rows, so first() is the current holder or null --}}
{{ $asset->staff->first()?->name ?? '-' }}
{{--
The line {{ $asset->staff->first()?->name ?? '-' }} reads from left to right:
1. $asset->staff is the list of people attached to this asset through the logbook (pivot table). Because of the filter in the controller, this list only holds people who haven’t returned it yet.
2. ->first() takes the first person from that list. Think of a queue at a kedai: first() picks the person at the front. If the queue is empty, it gives you null, which means “nobody”.
3. ?->name is the safe way to ask for the name. If first() found a person, you get their name. If it found nobody, the ? stops Laravel from crashing (it would otherwise say “trying to read name on null”) and just gives null again.
4. ?? '-' is the fallback. If everything before it ended up as null, show a dash instead.
5. {{ ... }} prints the final result on the page.
--}}
</td>
<td>
<a href="{{ route('assets.show', $asset) }}" class="btn btn-sm btn-info">View</a>
{{-- Edit and Delete are Admin only --}}
@if (auth()->user()->isAdmin())
<a href="{{ route('assets.edit', $asset) }}" class="btn btn-sm btn-warning">Edit</a>
<form method="POST" action="{{ route('assets.destroy', $asset) }}"
class="d-inline"
onsubmit="return confirm('Move this asset to the trash?')">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
@endif
</td>
</tr>
@empty
<tr>
<td colspan="7" class="text-center">No assets found.</td>
</tr>
@endforelse
</tbody>
</table>
{{ $assets->links() }}
@endsection
\ No newline at end of file
@extends('layouts.app')
@section('title', $asset->asset_tag)
@section('content')
{{--
The person holding this asset right now is the history row that has
no returned_at. first() with a function returns the first match,
or null if nobody holds it.
--}}
@php
$holder = $asset->staff->first(fn ($person) => $person->pivot->returned_at === null); // It looks through the asset’s history for the row with no return date. The result is the current holder, or null if nobody has it.
@endphp
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>{{ $asset->asset_tag }} &middot; {{ $asset->name }}</h1>
<div>
@if (auth()->user()->isAdmin())
<a href="{{ route('assets.edit', $asset) }}" class="btn btn-primary">Edit</a>
@endif
<a href="{{ route('assets.index') }}" class="btn btn-secondary">Back to list</a>
</div>
</div>
<table class="table">
<tr>
<th style="width: 200px;">Asset Tag</th>
<td>{{ $asset->asset_tag }}</td>
</tr>
<tr>
<th>Name</th>
<td>{{ $asset->name }}</td>
</tr>
<tr>
<th>Category</th>
<td>{{ $asset->category }}</td>
</tr>
<tr>
<th>Purchased</th>
<td>{{ $asset->purchase_date->format('d M Y') }}</td>
</tr>
<tr>
<th>Status</th>
<td><span class="badge text-bg-{{ $asset->badge() }}">{{ $asset->statusLabel() }}</span></td>
</tr>
<tr>
<th>Held by</th>
<td>
{{--This shows the holder’s name and the date they took it, or “Nobody”.--}}
@if ($holder)
{{ $holder->name }} since {{ \Carbon\Carbon::parse($holder->pivot->assigned_at)->format('d M Y') }}
@else
Nobody
@endif
</td>
</tr>
</table>
{{--
Assign or Return panel. Admin only, because the routes behind these
forms are protected by role:admin too.
- Available: show the Assign form
- In use: show the Return button
- Repair or disposed: nothing can be done, so we explain why
--}}
@if (auth()->user()->isAdmin())
<div class="card mb-4">
<div class="card-body">
@if ($asset->status === 'available')
<form method="POST" action="{{ route('assets.assignments.store', $asset) }}" class="row g-2 align-items-end">
@csrf
<div class="col-md-6">
<label for="staff_id" class="form-label">Assign to</label>
<select
name="staff_id"
id="staff_id"
class="form-select @error('staff_id') is-invalid @enderror"
>
<option value="">-- Select Staff --</option>
@foreach ($staffList as $person)
<option value="{{ $person->id }}" @selected(old('staff_id') == $person->id)>
{{ $person->name }} ({{ $person->staff_no }})
</option>
@endforeach
</select>
@error('staff_id')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-primary">Assign</button>
</div>
</form>
@elseif ($asset->status === 'in_use' && $holder)
<form method="POST" action="{{ route('assets.assignments.destroy', $asset) }}"
class="d-flex justify-content-between align-items-center"
onsubmit="return confirm('Mark this asset as returned?')">
@csrf
@method('DELETE')
<span>Currently with <strong>{{ $holder->name }}</strong>.</span>
<button type="submit" class="btn btn-outline-secondary">Return</button>
</form>
@else
<p class="mb-0 text-muted">
Only available assets can be assigned. This asset is {{ strtolower($asset->statusLabel()) }}.
</p>
@endif
</div>
</div>
@endif
<h2 class="h4 mt-4">Holder history</h2>
<table class="table table-bordered">
<thead class="table-light">
<tr>
<th>Staff</th>
<th>Assigned</th>
<th>Returned</th>
</tr>
</thead>
<tbody>
@forelse ($asset->staff as $person)
<tr>
<td>
{{-- Only link to the profile if this user is allowed to open it (StaffPolicy::view) --}}
@can('view', $person)
<a href="{{ route('staff.show', $person) }}">{{ $person->name }}</a>
@else
{{ $person->name }}
@endcan
</td>
{{-- Pivot dates come back as plain strings, so Carbon::parse() turns them into dates first --}}
<td>{{ \Carbon\Carbon::parse($person->pivot->assigned_at)->format('d M Y') }}</td>
<td>
@if ($person->pivot->returned_at)
{{ \Carbon\Carbon::parse($person->pivot->returned_at)->format('d M Y') }}
@else
<span class="badge text-bg-primary">Holding now</span>
@endif
</td>
</tr>
@empty
<tr>
<td colspan="3" class="text-center">This asset has never been assigned.</td>
</tr>
@endforelse
</tbody>
</table>
@endsection
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Asset Trash')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Trash</h1>
<a href="{{ route('assets.index') }}" class="btn btn-secondary">Back to assets</a>
</div>
<table class="table table-bordered table-hover">
<thead class="table-dark">
<tr>
<th>Tag</th>
<th>Name</th>
<th>Category</th>
<th>Deleted</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@forelse ($assets as $asset)
<tr>
<td>{{ $asset->asset_tag }}</td>
<td>{{ $asset->name }}</td>
<td>{{ $asset->category }}</td>
{{-- SoftDeletes casts deleted_at to a Carbon date for us, so format() works --}}
<td>{{ $asset->deleted_at->format('d M Y') }}</td>
<td>
{{--
Restore clears deleted_at. It is a PATCH because we are
changing an existing row, not creating or removing one.
--}}
<form method="POST" action="{{ route('assets.restore', $asset) }}" class="d-inline">
@csrf
@method('PATCH')
<button type="submit" class="btn btn-sm btn-success">Restore</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="5" class="text-center">The trash is empty.</td>
</tr>
@endforelse
</tbody>
</table>
{{ $assets->links() }}
@endsection
\ No newline at end of file
......@@ -14,6 +14,11 @@
Remember: hiding a link is not security. The controller or middleware
still blocks the URL. The sidebar only stops people seeing links
that would give them a 403.
The sidebar link is only for show, and the real lock is
Gate::authorize('viewAny', ...) in StaffController, where StaffPolicy
lets Admin through in before() and Manager through in viewAny(), so
Staff get a 403.
--}}
{{-- Departments: guarded by the role:admin middleware (not a Gate), so we check the role directly. --}}
......@@ -27,11 +32,10 @@
<a href="{{ route('staff.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('staff.*')])>Staff</a>
@endcan
{{-- Assets (Week 10): uncomment when the assets routes exist, otherwise route('assets.index') will crash.
{{-- Assets (Week 10): the view-assets Gate lets Admin and Manager see the link. --}}
@can('view-assets')
<a href="{{ route('assets.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('assets.*')])>Assets</a>
@endcan
--}}
{{-- Users: the manage-users Gate, same as UserController. Admin only. --}}
@can('manage-users')
......
......@@ -154,6 +154,14 @@
<td>{{ $s->position->name }}</td> {{-- Show the position name from the relationship, not a text field --}}
<td>{{ $s->join_date->format('d M Y') }}</td>
<td>
{{--
View opens the profile page (staff.show), where the
Current and Past assets are shown. The page is guarded
by StaffPolicy::view, so a Manager still cannot open
someone from another department.
--}}
<a href="{{ route('staff.show', $s) }}" class="btn btn-sm btn-outline-secondary">View</a>
<a href="{{ route('staff.edit', $s) }}" class="btn btn-sm btn-outline-primary">Edit</a>
{{--
......
......@@ -4,6 +4,10 @@
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.
Week 10: below the details we also show this person's assets,
Current (holding now) and Past (already returned), and Admins
get a checkbox form to assign more.
--}}
@extends('layouts.app')
......@@ -118,4 +122,143 @@
</table>
</div>
</div>
{{--
ASSETS (Week 10)
Anyone who may open this profile can see the Current and Past tables
(a Staff user sees their own equipment). The Assign form and the
Return buttons are Admin only, because the routes behind them are
protected by role:admin too.
--}}
<h2 class="h4 mt-4">Current assets</h2>
<table class="table table-bordered">
<thead class="table-light">
<tr>
<th>Tag</th>
<th>Name</th>
<th>Since</th>
@if (auth()->user()->isAdmin())
<th>Actions</th>
@endif
</tr>
</thead>
<tbody>
@forelse ($currentAssets as $asset)
<tr>
<td>
{{-- Only link to the asset page if this user may open it (the view-assets Gate) --}}
@can('view-assets')
<a href="{{ route('assets.show', $asset) }}">{{ $asset->asset_tag }}</a>
@else
{{ $asset->asset_tag }}
@endcan
</td>
<td>{{ $asset->name }}</td>
{{-- Pivot dates come back as plain strings, so Carbon::parse() turns them into dates first --}}
<td>{{ \Carbon\Carbon::parse($asset->pivot->assigned_at)->format('d M Y') }}</td>
@if (auth()->user()->isAdmin())
<td>
{{-- Same Return route as the asset page. back() brings you back here. --}}
<form method="POST" action="{{ route('assets.assignments.destroy', $asset) }}"
class="d-inline"
onsubmit="return confirm('Mark this asset as returned?')">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-outline-secondary">Return</button>
</form>
</td>
@endif
</tr>
@empty
<tr>
<td colspan="{{ auth()->user()->isAdmin() ? 4 : 3 }}" class="text-center">No assets assigned right now.</td>
</tr>
@endforelse
</tbody>
</table>
{{--
Checkbox assignment, Admin only.
name="asset_ids[]" sends the ticked boxes as an array of IDs.
@checked(in_array(...old('asset_ids', []))) keeps the ticks after
a failed save, the same idea as old() on text inputs.
--}}
@if (auth()->user()->isAdmin())
<div class="card mb-4">
<div class="card-body">
<h3 class="h5">Assign assets</h3>
<form method="POST" action="{{ route('staff.assets.store', $staff) }}">
@csrf
@forelse ($availableAssets as $available)
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
name="asset_ids[]"
id="asset_{{ $available->id }}"
value="{{ $available->id }}"
@checked(in_array($available->id, old('asset_ids', [])))
>
<label class="form-check-label" for="asset_{{ $available->id }}">
{{ $available->asset_tag }} &middot; {{ $available->name }}
</label>
</div>
@empty
<p class="text-muted mb-0">No available assets to assign.</p>
@endforelse
{{-- Errors for the whole list, or for any single ticked asset --}}
@error('asset_ids')
<div class="text-danger small mt-2">{{ $message }}</div>
@enderror
@error('asset_ids.*')
<div class="text-danger small mt-2">{{ $message }}</div>
@enderror
@if ($availableAssets->isNotEmpty())
<button type="submit" class="btn btn-primary mt-3">Assign selected</button>
@endif
</form>
</div>
</div>
@endif
<h2 class="h4 mt-4">Past assets</h2>
<table class="table table-bordered">
<thead class="table-light">
<tr>
<th>Tag</th>
<th>Name</th>
<th>Held from</th>
<th>Returned</th>
</tr>
</thead>
<tbody>
@forelse ($pastAssets as $asset)
<tr>
<td>
@can('view-assets')
<a href="{{ route('assets.show', $asset) }}">{{ $asset->asset_tag }}</a>
@else
{{ $asset->asset_tag }}
@endcan
</td>
<td>{{ $asset->name }}</td>
<td>{{ \Carbon\Carbon::parse($asset->pivot->assigned_at)->format('d M Y') }}</td>
<td>{{ \Carbon\Carbon::parse($asset->pivot->returned_at)->format('d M Y') }}</td>
</tr>
@empty
<tr>
<td colspan="4" class="text-center">No past assets.</td>
</tr>
@endforelse
</tbody>
</table>
@endsection
\ No newline at end of file
<?php
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\AssetAssignmentController;
use App\Http\Controllers\AssetController;
use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\PositionController;
use App\Http\Controllers\StaffAssetController;
use App\Http\Controllers\StaffController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
......@@ -68,6 +71,47 @@
->name('users.toggle');
Route::patch('users/{user}/reset-password', [UserController::class, 'resetPassword'])
->name('users.reset-password');
// Assets Trash page and Restore, Admin only.
// The trash route MUST be registered ABOVE the assets resource.
// Otherwise /assets/trash would be read as /assets/{asset} with an
// asset ID of "trash", and the page would 404.
Route::get('assets/trash', [AssetController::class, 'trash'])
->name('assets.trash');
// withTrashed() tells route model binding to also look among the
// deleted assets. Without it, a trashed asset returns a 404 here,
// so it could never be restored.
Route::patch('assets/{asset}/restore', [AssetController::class, 'restore'])
->name('assets.restore')
->withTrashed();
// Assets, Admin only part: add, edit and delete.
// except(['index', 'show']) leaves out the two read-only pages,
// because Managers may see those too (see the next block).
Route::resource('assets', AssetController::class)->except(['index', 'show']);
// Assign an asset to a staff member, and return it.
// Admin only, because they sit inside this role:admin group.
// The DELETE route does not delete anything, it closes the open
// logbook line by filling in returned_at.
Route::post('assets/{asset}/assignments', [AssetAssignmentController::class, 'store'])
->name('assets.assignments.store');
Route::delete('assets/{asset}/assignments', [AssetAssignmentController::class, 'destroy'])
->name('assets.assignments.destroy');
// Assign several assets to one staff member from the staff page
// (the checkbox form). Admin only, same reason as above.
Route::post('staff/{staff}/assets', [StaffAssetController::class, 'store'])
->name('staff.assets.store');
});
// Assets, read-only part: the list and the detail page.
// The view-assets Gate lets Admin and Manager through, Staff get a 403.
// This block MUST stay below the Admin block above. Otherwise
// /assets/create and /assets/trash would be read as /assets/{asset}.
Route::middleware('can:view-assets')->group(function () {
Route::resource('assets', AssetController::class)->only(['index', 'show']);
});
// CRUD modules from Month 1
......
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