🔧 Week 22, Day 3: Feature Integration & Bug Fixing
🎯 Learning Objectives
- Integrate frontend and backend components
- Implement borrowing system functionality
- Add email notifications
- Test all user flows and features
- Identify and fix common bugs
- Optimize application performance
- Use Git for version control and collaboration
🔗 Step 1: Complete Borrowing System
BorrowingController Implementation
// app/Http/Controllers/BorrowingController.php
namespace App\Http\Controllers;
use App\Models\Borrowing;
use App\Models\Book;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Notifications\BookBorrowedNotification;
use App\Notifications\BookReturnReminderNotification;
class BorrowingController extends Controller
{
public function index()
{
$borrowings = Borrowing::with(['book', 'user'])
->when(!Auth::user()->is_admin, function($query) {
$query->where('user_id', Auth::id());
})
->latest()
->paginate(15);
return view('borrowings.index', compact('borrowings'));
}
public function create()
{
$availableBooks = Book::where('available_quantity', '>', 0)->get();
return view('borrowings.create', compact('availableBooks'));
}
public function store(Request $request)
{
$validated = $request->validate([
'book_id' => 'required|exists:books,id',
'user_id' => 'required|exists:users,id',
'notes' => 'nullable|string|max:500'
]);
$book = Book::findOrFail($validated['book_id']);
// Check availability
if ($book->available_quantity < 1) {
return back()->with('error', 'This book is currently unavailable.');
}
// Create borrowing record
$borrowing = Borrowing::create([
'user_id' => $validated['user_id'],
'book_id' => $validated['book_id'],
'borrowed_date' => now(),
'due_date' => now()->addDays(14), // 14 days loan period
'status' => 'borrowed',
'notes' => $validated['notes']
]);
// Update book availability
$book->decrement('available_quantity');
// Send notification
$borrowing->user->notify(new BookBorrowedNotification($borrowing));
return redirect()->route('borrowings.index')
->with('success', 'Book borrowed successfully!');
}
public function return(Borrowing $borrowing)
{
// Check authorization
if (!Auth::user()->is_admin && $borrowing->user_id !== Auth::id()) {
abort(403, 'Unauthorized action.');
}
// Update borrowing
$borrowing->update([
'return_date' => now(),
'status' => 'returned'
]);
// Update book availability
$borrowing->book->increment('available_quantity');
// Check for overdue and create fine if necessary
if ($borrowing->return_date->isAfter($borrowing->due_date)) {
$daysOverdue = $borrowing->return_date->diffInDays($borrowing->due_date);
$fineAmount = $daysOverdue * 10; // 10 naira per day
$borrowing->fine()->create([
'amount' => $fineAmount,
'status' => 'pending'
]);
}
return redirect()->route('borrowings.index')
->with('success', 'Book returned successfully!');
}
public function destroy(Borrowing $borrowing)
{
// Only allow deletion if not returned
if ($borrowing->status === 'borrowed') {
$borrowing->book->increment('available_quantity');
}
$borrowing->delete();
return redirect()->route('borrowings.index')
->with('success', 'Borrowing record deleted.');
}
}
📧 Step 2: Email Notifications
Create Notification Classes
# Generate notifications
php artisan make:notification BookBorrowedNotification
php artisan make:notification BookReturnReminderNotification
Book Borrowed Notification
// app/Notifications/BookBorrowedNotification.php
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use App\Models\Borrowing;
class BookBorrowedNotification extends Notification
{
protected $borrowing;
public function __construct(Borrowing $borrowing)
{
$this->borrowing = $borrowing;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Book Borrowed Successfully')
->greeting('Hello ' . $notifiable->name . '!')
->line('You have successfully borrowed the following book:')
->line('**Book:** ' . $this->borrowing->book->title)
->line('**Author:** ' . $this->borrowing->book->author)
->line('**Borrowed Date:** ' . $this->borrowing->borrowed_date->format('M d, Y'))
->line('**Due Date:** ' . $this->borrowing->due_date->format('M d, Y'))
->line('Please return the book on or before the due date to avoid fines.')
->action('View My Borrowings', route('borrowings.index'))
->line('Thank you for using our library!');
}
}
Schedule Reminder Emails
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// Send reminder emails 2 days before due date
$schedule->call(function () {
$upcomingDue = Borrowing::where('status', 'borrowed')
->whereDate('due_date', now()->addDays(2))
->get();
foreach ($upcomingDue as $borrowing) {
$borrowing->user->notify(new BookReturnReminderNotification($borrowing));
}
})->daily();
// Mark overdue borrowings
$schedule->call(function () {
Borrowing::where('status', 'borrowed')
->whereDate('due_date', '<', now())
->update(['status' => 'overdue']);
})->daily();
}
🐛 Step 3: Common Bugs & Fixes
Bug Tracking Checklist
| Issue |
Symptom |
Solution |
| Image not displaying |
Broken image icons |
Run php artisan storage:link |
| Validation errors not showing |
Form submits without feedback |
Add @error directives in Blade |
| Relationship not loading |
N+1 query problem |
Use ->with(['relation']) eager loading |
| Pagination links broken |
Page numbers don't preserve filters |
Use ->appends(request()->query()) |
| Old input not retained |
Form clears on validation error |
Use old('field_name') in inputs |
| Unauthorized access |
Users can access restricted pages |
Add middleware or authorization checks |
Fixing Search Functionality
// Update BookController@index with search
public function index(Request $request)
{
$query = Book::with('category');
// Search filter
if ($request->filled('search')) {
$search = $request->search;
$query->where(function($q) use ($search) {
$q->where('title', 'like', "%{$search}%")
->orWhere('author', 'like', "%{$search}%")
->orWhere('isbn', 'like', "%{$search}%");
});
}
// Category filter
if ($request->filled('category')) {
$query->where('category_id', $request->category);
}
// Availability filter
if ($request->filled('available')) {
if ($request->available === 'yes') {
$query->where('available_quantity', '>', 0);
} else {
$query->where('available_quantity', '=', 0);
}
}
$books = $query->latest()->paginate(12)->appends($request->query());
$categories = Category::all();
return view('books.index', compact('books', 'categories'));
}
🚀 Step 4: Performance Optimization
Optimization Techniques
1. Database Query Optimization
// Bad - N+1 query problem
$borrowings = Borrowing::all();
foreach ($borrowings as $borrowing) {
echo $borrowing->book->title; // Separate query each time
}
// Good - Eager loading
$borrowings = Borrowing::with(['book', 'user'])->get();
foreach ($borrowings as $borrowing) {
echo $borrowing->book->title; // No extra queries
}
2. Caching Common Data
// Cache categories for 1 hour
$categories = Cache::remember('categories', 3600, function () {
return Category::all();
});
3. Image Optimization
// Install Intervention Image
composer require intervention/image
// Resize uploaded images
use Intervention\Image\Facades\Image;
if ($request->hasFile('cover_image')) {
$image = $request->file('cover_image');
$filename = time() . '.' . $image->extension();
$path = public_path('storage/book-covers/' . $filename);
Image::make($image)->resize(400, 600)->save($path);
$validated['cover_image'] = 'book-covers/' . $filename;
}
📱 Step 5: Git Version Control
Git Workflow for Team Collaboration
Initial Setup
# Initialize Git repository
git init
# Add .gitignore
echo "node_modules/
/vendor/
.env
/storage/*.key
/public/hot
/public/storage" > .gitignore
# Initial commit
git add .
git commit -m "Initial commit: Laravel project setup"
# Create GitHub repository and push
git remote add origin https://github.com/yourusername/library-system.git
git branch -M main
git push -u origin main
Team Workflow
# Create feature branch
git checkout -b feature/borrowing-system
# Make changes and commit
git add .
git commit -m "Add borrowing system with email notifications"
# Push to GitHub
git push origin feature/borrowing-system
# Create Pull Request on GitHub
# After review, merge to main branch
# Update local main branch
git checkout main
git pull origin main
Useful Git Commands
# Check status
git status
# View changes
git diff
# View commit history
git log --oneline
# Undo uncommitted changes
git checkout -- filename
# Create and switch to new branch
git checkout -b branch-name
# Switch branches
git checkout branch-name
# Merge branch into current branch
git merge branch-name
✏️ Today's Tasks
Task 1: Complete Borrowing System (90 minutes)
- Implement BorrowingController with all methods
- Create borrowing views (index, create)
- Add return book functionality
- Test borrowing flow end-to-end
- Verify book availability updates correctly
Task 2: Add Email Notifications (45 minutes)
- Create notification classes
- Configure SMTP in .env
- Test email sending
- Schedule reminder emails
Task 3: Bug Fixing Sprint (60 minutes)
- Test all CRUD operations
- Fix validation issues
- Fix image upload and display
- Fix search and filter functionality
- Test on different browsers
Task 4: Performance Optimization (30 minutes)
- Add eager loading to prevent N+1 queries
- Optimize database indexes
- Add caching for categories
- Resize uploaded images
Task 5: Git Version Control (30 minutes)
- Initialize Git repository
- Commit all changes
- Push to GitHub
- Add team members as collaborators
📦 Deliverables
By end of day:
- Integrated Application:
- All modules working together
- Complete user flows functional
- No critical bugs
- Working Features:
- User authentication
- Book management (CRUD)
- Borrowing system
- Email notifications
- Search and filtering
- Code Quality:
- Clean, readable code
- Proper error handling
- Optimized queries
- Version Control:
- GitHub repository created
- All code committed
- Team members added
💡 Testing Checklist:
- ✅ Can users register and login?
- ✅ Can books be added, edited, and deleted?
- ✅ Does search return correct results?
- ✅ Can books be borrowed and returned?
- ✅ Do email notifications work?
- ✅ Does pagination work with filters?
- ✅ Are validation errors displayed properly?
- ✅ Do images upload and display correctly?
- ✅ Is the site responsive on mobile?
⚠️ Don't forget: Commit your code to Git regularly! Use meaningful commit messages like "Add borrowing system" or "Fix image upload bug".