Commit 2019b9cf by Amshar

WEEK 6 - VALIDATION, FORM REQUESTS, SEARCH & PAGINATION

parent 65e77812
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreStaffRequest;
use App\Http\Requests\UpdateStaffRequest;
use App\Models\Staff;
use App\Models\Department;
use Illuminate\Http\Request;
class StaffController extends Controller
{
/**
* REASON FOR Request $request
* The search box and department dropdown send data through the URL,
* like ?search=aina&department=3. The $request object is how you read
* those values inside the controller.
*
* Without it, you’d have no way to know what the user typed in the search
* box or which department they picked from the filter. $request->search gives
* you the search term, and $request->department gives you the department ID.
*
* The other methods like create() and show() don’t need it because they
* don’t read any input from the URL. They just show a form or a record.
*
* Display the staff list with search, filter and pagination.
* This method does a lot, so here's the flow:
* 1. Eager-load departments to avoid N+1 queries
* 2. If the user typed a search term, filter by name, staff_no or email
* 3. If the user picked a department from the dropdown, filter by that too
* 4. Sort by name A-Z
* 5. Show 10 per page, keeping the search and filter in the page links
*/
public function index(Request $request)
{
// Validate the sort value — only allow these three options.
// If someone tampers with the URL and sends ?sort=hackme,
// Laravel rejects it silently and $sort stays null.
$sort = in_array($request->sort, ['name', 'newest', 'department'])
? $request->sort
: 'name';
$staff = Staff::with('department')
->when($request->search, function ($query, $term) {
// Wrap the OR conditions in a group so the department
// filter still works. Without the group, a department
// filter + search could return staff from other departments
// if their name matches.
$query->where(function ($q) use ($term) {
$q->where('name', 'like', "%{$term}%")
->orWhere('staff_no', 'like', "%{$term}%")
->orWhere('email', 'like', "%{$term}%");
});
})
->when($request->department, function ($query, $departmentId) {
// Filter by the department ID from the dropdown
$query->where('department_id', $departmentId);
})
// Sort based on the dropdown selection
->when($sort === 'newest', function ($query) {
// Most recent join date first
$query->orderBy('join_date', 'desc');
})
->when($sort === 'department', function ($query) {
// Sort by department name using a subquery.
// We can't do orderBy('department.name') directly because
// eager loading (with()) runs a separate query. So we use
// a subquery that looks up the department name for each row.
$query->orderBy(
Department::select('name')
->whereColumn('departments.id', 'staff.department_id')
);
})
->when($sort === 'name', function ($query) {
$query->orderBy('name');
})
->paginate(10)
->withQueryString();
// The department list is for the filter dropdown, not the staff data
$departments = Department::orderBy('name')->get();
return view('staff.index', compact('staff', 'departments')); //The result of quuery above is stored in $staff, which then gets passed to the view
}
/**
* Show the form for creating a new staff member.
*
* We need the department list for the dropdown, sorted by name
* so the user can find theirs quickly.
*/
public function create()
{
$departments = Department::orderBy('name')->get();
return view('staff.create', compact('departments'));
}
/**
* Save a new staff member to the database.
*
* Notice we 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.
*/
public function store(StoreStaffRequest $request)
{
Staff::create($request->validated());
return redirect()->route('staff.index')
->with('success', 'Staff member added.');
}
/**
* Display the specified resource.
*/
public function show(Staff $staff)
{
//
}
/**
* Show the form for editing an existing staff member.
*
* Same department list as create(), plus the staff record
* whose fields we want to fill the form with.
*/
public function edit(Staff $staff)
{
$departments = Department::orderBy('name')->get();
return view('staff.edit', compact('staff', 'departments'));
}
/**
* 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."
*/
public function update(UpdateStaffRequest $request, Staff $staff)
{
$staff->update($request->validated());
return redirect()->route('staff.index')
->with('success', 'Staff updated.');
}
/**
* Delete a staff member.
*
* 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)
{
$staff->delete();
return back()->with('success', 'Staff member deleted.');
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
class StoreStaffRequest extends FormRequest
{
/**
* Who is allowed to use this request?
*
* For now, any logged-in user can add staff.
* In Month 3 you'll add role checks here instead.
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* The validation rules for creating a new staff member.
*
* Every rule here must pass before the controller's store()
* method even runs. If anything fails, Laravel redirects back
* to the form with error messages and the old input.
*/
public function rules(): array
{
return [
'staff_no' => 'required|max:20|unique:staff',
'name' => 'required|max:100',
'email' => 'required|email|unique:staff',
'department_id' => 'required|exists:departments,id',
'position' => 'required|max:100',
'join_date' => 'required|date|before_or_equal:today',
];
}
/**
* Custom error messages.
*
* Laravel's defaults are fine for most rules, but some deserve
* friendlier wording. Only override the ones worth improving.
*/
public function messages(): array
{
return [
'staff_no.unique' => 'This staff number is already taken.',
'email.unique' => 'This email address is already in use.',
'department_id.exists' => 'Please select a valid department.',
'join_date.before_or_equal' => 'The join date cannot be in the future.',
];
}
}
\ No newline at end of file
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule; // This Rule class is use in this file and not at the StoreStaffRequest.php because:
/*
Creating = the value should not exist at all, so unique:staff is enough.
Updating = the value already exists because it belongs to the record being edited,
so you need ignore() to skip that record. That requires the Rule class.
Say Aina has staff number S-0101. She opens her edit form, changes only her position
title, and hits save. Laravel checks “is S-0101 already in the staff table?” and finds it,
because it’s Aina’s own record. Without ignore(), Laravel would reject the form saying
“this staff number is already taken,” even though it’s her own number she’s keeping.
*/
class UpdateStaffRequest extends FormRequest
{
/**
* Who is allowed to use this request?
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* The validation rules for updating an existing staff member.
*
* Almost the same as StoreStaffRequest, with one key difference:
* the unique rules for staff_no and email use Rule::unique()->ignore()
* so a staff member can keep their own number and email without
* Laravel complaining "already taken" — because of course it is,
* it's theirs!
*
* $this->route('staff') grabs the Staff model from the URL
* (e.g. /staff/7 gives us Staff #7) thanks to route model binding.
*/
public function rules(): array
{
return [
'staff_no' => [
'required',
'max:20',
Rule::unique('staff')->ignore($this->route('staff')),
],
'name' => 'required|max:100',
'email' => [
'required',
'email',
Rule::unique('staff')->ignore($this->route('staff')),
],
'department_id' => 'required|exists:departments,id',
'position' => 'required|max:100',
'join_date' => 'required|date|before_or_equal:today',
];
}
/**
* Custom error messages — same as StoreStaffRequest.
*/
public function messages(): array
{
return [
'staff_no.unique' => 'This staff number is already taken.',
'email.unique' => 'This email address is already in use.',
'department_id.exists' => 'Please select a valid department.',
'join_date.before_or_equal' => 'The join date cannot be in the future.',
];
}
}
\ No newline at end of file
...@@ -23,6 +23,16 @@ class Staff extends Model ...@@ -23,6 +23,16 @@ class Staff extends Model
'join_date', 'join_date',
]; ];
// Tell Laravel to convert these columns into proper data types.
// Without this, join_date is just a plain string like "2026-10-01"
// and you can't call ->format() on it. With the cast, Laravel
// turns it into a Carbon date object, which gives you methods
// like ->format('d M Y') for display and ->diffForHumans() for
// "2 days ago" style output.
protected $casts = [
'join_date' => 'date',
];
/** /**
* A staff member belongs to one department. * A staff member belongs to one department.
* Laravel looks for a department_id column on this table * Laravel looks for a department_id column on this table
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
<p class="text-muted text-uppercase small fw-bold mb-1 px-3">Modules</p> <p class="text-muted text-uppercase small fw-bold mb-1 px-3">Modules</p>
<a href="{{ route('departments.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('departments.*')])>Departments</a> <a href="{{ route('departments.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('departments.*')])>Departments</a>
<a href="{{ route('positions.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('positions.*')])>Positions</a> <a href="{{ route('positions.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('positions.*')])>Positions</a>
<a href="{{ route('staff.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('staff.*')])>Staff</a>
</nav> </nav>
{{-- {{--
......
{{--
THIS FILE IS BASICALLY THE TEMPLATE FORM THAT WILL BE USED BY ALL THE FORMS IN /staff FOLDER.
THEREFORE, IT WILL BE USED BY EDIT AND CREATE PAGE FILES (create.blade.php and edit.blade.php)
Shared form fields for staff 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 $staff variable may or may not exist:
- Create page: $staff is not set, so old() has no fallback
- Edit page: $staff is passed in, so old() falls back to the saved value
--}}
<div class="row mb-3">
{{--
Staff Number
maxlength="20" matches the max:20 rule in the Form Request.
This stops the browser from letting the user type more than
20 characters, but we still validate on the server because
someone could bypass the browser limit using DevTools.
--}}
<div class="col-md-6">
<label for="staff_no" class="form-label">Staff No</label>
<input
type="text"
name="staff_no"
id="staff_no"
class="form-control @error('staff_no') is-invalid @enderror"
value="{{ old('staff_no', $staff->staff_no ?? '') }}"
maxlength="20"
>
{{--
For
This asks two questions in order: value="{{ old('staff_no', $staff->staff_no ?? '') }}"
- Did the user just try to save and fail? Show what they typed. (That’s old())
- If not, are we editing someone? Show their saved data. (That’s $staff->email)
- If neither, leave it empty. (That’s the '' at the end)
--}}
{{--
@error('staff_no') checks if validation failed for this field.
If it did, Bootstrap's is-invalid class (above) turns the
border red, and this div shows the error message underneath.
$message comes from the Form Request — either Laravel's
default or our custom message like "This staff number is
already taken."
--}}
@error('staff_no')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
{{--
For <div class="invalid-feedback">{{ $message }}</div>
If there’s an error, show it in red text below the field. Something like
“This email address is already in use.” If no error, this whole block is hidden.
--}}
</div>
{{--class="form-control @error('name') is-invalid @enderror" turns the border red when there's error--}}
{{-- 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', $staff->name ?? '') }}"
maxlength="100"
>
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
{{--
Email
type="email" gives basic browser-side format checking,
but the real validation happens in the Form Request with
the 'email' rule, which is stricter.
--}}
<div class="col-md-6">
<label for="email" class="form-label">Email</label>
<input
type="email"
name="email"
id="email"
class="form-control @error('email') is-invalid @enderror"
value="{{ old('email', $staff->email ?? '') }}"
>
@error('email')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
{{--
Department Dropdown
Instead of letting the user type a department name (which
could be misspelled or made up), we show a <select> with
only valid departments from the database. The value sent
to the server is the department's ID, not its name.
The Form Request rule 'exists:departments,id' double-checks
that the ID actually exists, in case someone tampers with
the form using DevTools.
--}}
<div class="col-md-6">
<label for="department_id" class="form-label">Department</label>
<select
name="department_id"
id="department_id"
class="form-select @error('department_id') is-invalid @enderror"
>
{{-- The empty first option forces the user to make a choice --}}
<option value="">-- Select Department --</option>
@foreach ($departments as $department)
{{--
@selected() outputs the 'selected' attribute when true.
old('department_id', $staff->department_id ?? '') works
the same way as the text inputs:
1. If the form just failed, old() returns what the user
picked before the error
2. On the edit page's first load, it falls back to the
staff member's current department
3. On the create page's first load, it's empty so
nothing is pre-selected
--}}
<option
value="{{ $department->id }}"
@selected(old('department_id', $staff->department_id ?? '') == $department->id)
>
{{ $department->name }}
</option>
@endforeach
</select>
@error('department_id')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
{{-- Position --}}
<div class="col-md-6">
<label for="position" class="form-label">Position</label>
<input
type="text"
name="position"
id="position"
class="form-control @error('position') is-invalid @enderror"
value="{{ old('position', $staff->position ?? '') }}"
maxlength="100"
>
@error('position')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
{{--
Join Date
type="date" shows a date picker in most browsers.
The value format must be Y-m-d (e.g. 2026-10-01) for the
browser to understand it. That's why on edit we use
$staff->join_date->format('Y-m-d') instead of the raw value.
isset($staff) checks if we're on the edit page. We can't use
$staff->join_date ?? '' here because calling ->format() on
null would crash. So we check first: if $staff exists, format
the date; if not, leave it empty.
--}}
<div class="col-md-6">
<label for="join_date" class="form-label">Join Date</label>
<input
type="date"
name="join_date"
id="join_date"
class="form-control @error('join_date') is-invalid @enderror"
value="{{ old('join_date', isset($staff) ? $staff->join_date->format('Y-m-d') : '') }}"
>
@error('join_date')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
\ No newline at end of file
{{--
Create a new staff member.
This view extends the main app layout (with sidebar, header, etc.)
and fills in the 'title' and 'content' sections.
The form POSTs to staff.store, which is handled by
StaffController@store. But before store() runs, Laravel
passes the data through StoreStaffRequest first to check
all the validation rules. If anything fails, Laravel
redirects right back here with error messages.
--}}
@extends('layouts.app')
@section('title', 'Add Staff')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Add Staff</h1>
</div>
{{--
method="POST" because we're creating something new.
The edit form uses @method('PUT') instead, but create
just needs a plain POST.
--}}
<form method="POST" action="{{ route('staff.store') }}">
{{--
@csrf adds a hidden token field to the form.
It proves this form was submitted from our own site,
not by an attacker tricking someone into clicking
a fake form on another website.
--}}
@csrf
{{--
@include pulls in the shared _form partial.
The same six fields appear on both create and edit,
so they live in one file instead of being duplicated.
On this page $staff doesn't exist yet, so old() has
no fallback and the fields start empty.
--}}
@include('staff._form')
<div class="mt-3">
<button type="submit" class="btn btn-primary">Save</button>
{{-- Cancel takes the user back to the staff list without saving --}}
<a href="{{ route('staff.index') }}" class="btn btn-secondary">Cancel</a>
</div>
</form>
@endsection
\ No newline at end of file
{{--
Edit an existing staff member.
This view looks almost identical to create.blade.php because
both pages use the same shared _form partial. The differences:
1. The form action points to staff.update instead of staff.store
2. We add @method('PUT') because HTML forms only support GET and POST,
so Laravel uses a hidden _method field to know this is an update
3. The $staff variable is passed in, so old() falls back to the
saved values when the form first loads (e.g. the name field
shows the staff member's current name)
--}}
@extends('layouts.app')
@section('title', 'Edit Staff')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Edit Staff</h1>
</div>
{{--
route('staff.update', $staff) generates a URL like /staff/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) }}">
{{--
@csrf is the same security token as the create form.
Every form needs it, whether creating or editing.
--}}
@csrf
{{--
@method('PUT') adds a hidden field: <input name="_method" value="PUT">
Browsers can only send GET and POST requests from a form.
Laravel reads this hidden field and treats the request as PUT,
which routes it to StaffController@update instead of @store.
--}}
@method('PUT')
{{--
Same shared partial as create, but this time $staff exists.
So old('name', $staff->name) shows the saved name on first load,
and shows whatever the user typed if validation fails.
--}}
@include('staff._form')
<div class="mt-3">
<button type="submit" class="btn btn-primary">Update</button>
{{-- Cancel takes the user back to the staff list without saving --}}
<a href="{{ route('staff.index') }}" class="btn btn-secondary">Cancel</a>
</div>
</form>
@endsection
\ No newline at end of file
{{--
Staff list page with search, department filter and pagination.
This is the main page for the Staff module. It shows a table
of all staff members with their department, and lets you search
by name, staff number or email, and filter by department.
--}}
@extends('layouts.app')
@section('title', 'Staff')
@section('content')
{{-- Page header with title and Add button --}}
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Staff</h1>
<a href="{{ route('staff.create') }}" class="btn btn-primary">+ Add</a>
</div>
{{--
Search and filter form.
method="GET" keeps the filters in the URL as query strings
like ?search=aina&department=3. This means:
- The user can bookmark or share filtered results
- The browser Back button works as expected
- Refreshing the page keeps the filters
--}}
<form method="GET" action="{{ route('staff.index') }}" class="row g-2 mb-3">
{{-- Search box --}}
<div class="col-md-5">
<input
type="text"
name="search"
class="form-control"
placeholder="Search name, staff no or email..."
value="{{ request('search') }}"
>
</div>
{{-- Department filter dropdown --}}
<div class="col-md-4">
<select name="department" class="form-select">
<option value="">All departments</option>
@foreach ($departments as $department)
{{--
request('department') reads the current filter
from the URL so it stays selected after filtering
--}}
<option
value="{{ $department->id }}"
@selected(request('department') == $department->id)
>
{{ $department->name }}
</option>
@endforeach
</select>
</div>
{{--
Sort dropdown.
The three options match exactly what the controller accepts.
request('sort') keeps the selected option after filtering,
just like the department dropdown.
--}}
<div class="col-md-2">
<select name="sort" class="form-select">
<option value="name" @selected(request('sort') === 'name')>Name</option>
<option value="newest" @selected(request('sort') === 'newest')>Newest</option>
<option value="department" @selected(request('sort') === 'department')>Department</option>
</select>
</div>
{{-- Filter button submits the form as GET --}}
<div class="col-md-3">
<button type="submit" class="btn btn-primary">Filter</button>
{{--
Clear link resets everything by going to the base URL
without any query strings
--}}
<a href="{{ route('staff.index') }}" class="btn btn-secondary">Clear</a>
</div>
</form>
{{-- Staff table --}}
<table class="table table-hover">
<thead>
<tr>
<th>Staff No</th>
<th>Name</th>
<th>Email</th>
<th>Department</th>
<th>Position</th>
<th>Join Date</th>
<th></th>
</tr>
</thead>
<tbody>
{{--
@forelse is like @foreach but with a built-in @empty block.
If the query returns no results (no staff at all, or nothing
matching the search), it shows the empty state instead.
--}}
@forelse ($staff as $s)
<tr>
<td>{{ $s->staff_no }}</td>
<td>{{ $s->name }}</td>
<td>{{ $s->email }}</td>
{{--
$s->department->name works without an extra query
because we used with('department') in the controller.
Without eager loading, this would run one query per row.
--}}
<td>{{ $s->department->name }}</td>
<td>{{ $s->position }}</td>
<td>{{ $s->join_date->format('d M Y') }}</td>
<td>
<a href="{{ route('staff.edit', $s) }}" class="btn btn-sm btn-outline-primary">Edit</a>
{{--
Delete form — uses a button inside a form instead of a link,
because DELETE must be a POST with @method('DELETE').
The onsubmit confirm gives the user a chance to cancel.
--}}
<form
method="POST"
action="{{ route('staff.destroy', $s) }}"
class="d-inline"
onsubmit="return confirm('Delete {{ $s->name }}?')"
>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</td>
</tr>
@empty
{{-- Shown when no staff match the search or filter --}}
<tr>
<td colspan="7" class="text-center text-muted py-4">
No staff found.
</td>
</tr>
@endforelse
</tbody>
</table>
{{--
Pagination links.
withQueryString() in the controller ensures that clicking
page 2 keeps ?search=aina&department=3 in the URL.
Without it, changing pages would lose the filters.
--}}
{{ $staff->links() }}
@endsection
\ No newline at end of file
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
use App\Http\Controllers\DepartmentController; use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\PageController; use App\Http\Controllers\PageController;
use App\Http\Controllers\PositionController; use App\Http\Controllers\PositionController;
use App\Http\Controllers\StaffController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
/* /*
...@@ -49,6 +50,7 @@ ...@@ -49,6 +50,7 @@
// CRUD modules from Month 1 // CRUD modules from Month 1
Route::resource('departments', DepartmentController::class); Route::resource('departments', DepartmentController::class);
Route::resource('positions', PositionController::class); Route::resource('positions', PositionController::class);
Route::resource('staff', StaffController::class);
}); });
/* CHANGE FROM Route::middleware('auth')... to Route::middleware(['auth', 'active']) /* 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