💻 Week 22, Day 1: Backend Development Kickoff

🎯 Learning Objectives

🚀 Step 1: Project Setup & Environment

Initial Setup Checklist

1. Create Laravel Project

# Create new Laravel project
composer create-project laravel/laravel library-system

# Navigate to project
cd library-system

# Install Laravel Breeze for authentication
composer require laravel/breeze --dev
php artisan breeze:install

# Install npm dependencies
npm install
npm run dev

# Create database (in phpMyAdmin or MySQL)
# Database name: library_system

2. Configure Environment (.env)

APP_NAME="Library Management System"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=library_system
DB_USERNAME=root
DB_PASSWORD=

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

3. Run Initial Migration

php artisan migrate

🗄️ Step 2: Database Design & Migrations

Example: Library Management System Migrations

Create Migrations

# Create all migrations
php artisan make:migration create_categories_table
php artisan make:migration create_books_table
php artisan make:migration create_borrowings_table
php artisan make:migration create_fines_table

1. Categories Migration

// database/migrations/xxxx_create_categories_table.php
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

2. Books Migration

// database/migrations/xxxx_create_books_table.php
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('author');
        $table->string('isbn')->unique();
        $table->foreignId('category_id')->constrained()->onDelete('cascade');
        $table->text('description')->nullable();
        $table->integer('quantity')->default(1);
        $table->integer('available_quantity')->default(1);
        $table->string('cover_image')->nullable();
        $table->year('publication_year')->nullable();
        $table->timestamps();
    });
}

3. Borrowings Migration

// database/migrations/xxxx_create_borrowings_table.php
public function up()
{
    Schema::create('borrowings', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
        $table->foreignId('book_id')->constrained()->onDelete('cascade');
        $table->date('borrowed_date');
        $table->date('due_date');
        $table->date('return_date')->nullable();
        $table->enum('status', ['borrowed', 'returned', 'overdue'])->default('borrowed');
        $table->text('notes')->nullable();
        $table->timestamps();
    });
}

4. Fines Migration

// database/migrations/xxxx_create_fines_table.php
public function up()
{
    Schema::create('fines', function (Blueprint $table) {
        $table->id();
        $table->foreignId('borrowing_id')->constrained()->onDelete('cascade');
        $table->decimal('amount', 8, 2);
        $table->timestamp('paid_at')->nullable();
        $table->enum('status', ['pending', 'paid'])->default('pending');
        $table->timestamps();
    });
}

Run Migrations

php artisan migrate

📦 Step 3: Eloquent Models

Create Models with Relationships

Generate Models

php artisan make:model Category
php artisan make:model Book
php artisan make:model Borrowing
php artisan make:model Fine

1. Category Model

// app/Models/Category.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description'];

    // One category has many books
    public function books()
    {
        return $this->hasMany(Book::class);
    }
}

2. Book Model

// app/Models/Book.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'author', 'isbn', 'category_id', 
        'description', 'quantity', 'available_quantity', 
        'cover_image', 'publication_year'
    ];

    // Book belongs to a category
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    // Book has many borrowings
    public function borrowings()
    {
        return $this->hasMany(Borrowing::class);
    }

    // Check if book is available
    public function isAvailable()
    {
        return $this->available_quantity > 0;
    }
}

3. Borrowing Model

// app/Models/Borrowing.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Borrowing extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'book_id', 'borrowed_date', 
        'due_date', 'return_date', 'status', 'notes'
    ];

    protected $casts = [
        'borrowed_date' => 'date',
        'due_date' => 'date',
        'return_date' => 'date',
    ];

    // Borrowing belongs to a user
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Borrowing belongs to a book
    public function book()
    {
        return $this->belongsTo(Book::class);
    }

    // Borrowing has one fine
    public function fine()
    {
        return $this->hasOne(Fine::class);
    }

    // Check if borrowing is overdue
    public function isOverdue()
    {
        return $this->status === 'overdue' || 
               ($this->status === 'borrowed' && now()->isAfter($this->due_date));
    }
}

4. Fine Model

// app/Models/Fine.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Fine extends Model
{
    use HasFactory;

    protected $fillable = ['borrowing_id', 'amount', 'paid_at', 'status'];

    protected $casts = [
        'paid_at' => 'datetime',
        'amount' => 'decimal:2',
    ];

    // Fine belongs to a borrowing
    public function borrowing()
    {
        return $this->belongsTo(Borrowing::class);
    }
}

5. Update User Model

// app/Models/User.php
// Add this method to the User model

public function borrowings()
{
    return $this->hasMany(Borrowing::class);
}

public function activeBorrowings()
{
    return $this->hasMany(Borrowing::class)
                ->where('status', 'borrowed');
}

🎮 Step 4: Controllers

Create Resource Controllers

# Generate controllers
php artisan make:controller BookController --resource
php artisan make:controller BorrowingController --resource
php artisan make:controller CategoryController --resource
php artisan make:controller DashboardController

Example: BookController

// app/Http/Controllers/BookController.php
namespace App\Http\Controllers;

use App\Models\Book;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BookController extends Controller
{
    // Display all books
    public function index()
    {
        $books = Book::with('category')
                     ->latest()
                     ->paginate(12);
        
        return view('books.index', compact('books'));
    }

    // Show create form
    public function create()
    {
        $categories = Category::all();
        return view('books.create', compact('categories'));
    }

    // Store new book
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:255',
            'isbn' => 'required|unique:books,isbn',
            'category_id' => 'required|exists:categories,id',
            'description' => 'nullable|string',
            'quantity' => 'required|integer|min:1',
            'publication_year' => 'nullable|integer|min:1900|max:' . date('Y'),
            'cover_image' => 'nullable|image|max:2048'
        ]);

        // Handle file upload
        if ($request->hasFile('cover_image')) {
            $validated['cover_image'] = $request->file('cover_image')
                                                ->store('book-covers', 'public');
        }

        $validated['available_quantity'] = $validated['quantity'];

        Book::create($validated);

        return redirect()->route('books.index')
                        ->with('success', 'Book added successfully!');
    }

    // Show single book
    public function show(Book $book)
    {
        $book->load('category', 'borrowings.user');
        return view('books.show', compact('book'));
    }

    // Show edit form
    public function edit(Book $book)
    {
        $categories = Category::all();
        return view('books.edit', compact('book', 'categories'));
    }

    // Update book
    public function update(Request $request, Book $book)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:255',
            'isbn' => 'required|unique:books,isbn,' . $book->id,
            'category_id' => 'required|exists:categories,id',
            'description' => 'nullable|string',
            'quantity' => 'required|integer|min:1',
            'publication_year' => 'nullable|integer|min:1900|max:' . date('Y'),
            'cover_image' => 'nullable|image|max:2048'
        ]);

        if ($request->hasFile('cover_image')) {
            // Delete old image
            if ($book->cover_image) {
                Storage::disk('public')->delete($book->cover_image);
            }
            $validated['cover_image'] = $request->file('cover_image')
                                                ->store('book-covers', 'public');
        }

        $book->update($validated);

        return redirect()->route('books.show', $book)
                        ->with('success', 'Book updated successfully!');
    }

    // Delete book
    public function destroy(Book $book)
    {
        if ($book->cover_image) {
            Storage::disk('public')->delete($book->cover_image);
        }

        $book->delete();

        return redirect()->route('books.index')
                        ->with('success', 'Book deleted successfully!');
    }
}

🛣️ Step 5: Routes Setup

Configure Web Routes

// routes/web.php
use App\Http\Controllers\BookController;
use App\Http\Controllers\BorrowingController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\DashboardController;

// Public routes
Route::get('/', function () {
    return view('welcome');
});

// Authentication routes (provided by Breeze)
require __DIR__.'/auth.php';

// Protected routes
Route::middleware(['auth'])->group(function () {
    
    // Dashboard
    Route::get('/dashboard', [DashboardController::class, 'index'])
         ->name('dashboard');
    
    // Books
    Route::resource('books', BookController::class);
    
    // Borrowings
    Route::resource('borrowings', BorrowingController::class);
    Route::post('borrowings/{borrowing}/return', [BorrowingController::class, 'return'])
         ->name('borrowings.return');
    
    // Categories (admin only)
    Route::middleware(['role:admin'])->group(function () {
        Route::resource('categories', CategoryController::class);
    });
});

🌱 Step 6: Database Seeding

Create Seeders for Test Data

Category Seeder

php artisan make:seeder CategorySeeder

// database/seeders/CategorySeeder.php
public function run()
{
    $categories = [
        ['name' => 'Fiction', 'description' => 'Novels and fictional stories'],
        ['name' => 'Science', 'description' => 'Scientific books and research'],
        ['name' => 'Technology', 'description' => 'Computer science and IT books'],
        ['name' => 'History', 'description' => 'Historical books and biographies'],
        ['name' => 'Education', 'description' => 'Educational and textbooks'],
    ];

    foreach ($categories as $category) {
        Category::create($category);
    }
}

Run Seeder

php artisan db:seed --class=CategorySeeder

✏️ Today's Tasks

Task 1: Project Setup (30 minutes)

  1. Create new Laravel project
  2. Install Laravel Breeze
  3. Configure .env file with database credentials
  4. Test that authentication works

Task 2: Create Migrations (45 minutes)

  1. Create all 4 migration files (categories, books, borrowings, fines)
  2. Define table structure with proper columns and relationships
  3. Run migrations and verify tables in phpMyAdmin

Task 3: Build Models (45 minutes)

  1. Create all model files
  2. Define relationships (hasMany, belongsTo, hasOne)
  3. Add fillable properties
  4. Add helper methods (isAvailable, isOverdue)

Task 4: Create Controllers (60 minutes)

  1. Generate resource controllers
  2. Implement BookController with all CRUD methods
  3. Add validation rules
  4. Test controller methods

Task 5: Setup Routes (15 minutes)

  1. Configure web.php with all routes
  2. Add authentication middleware
  3. Test routes with php artisan route:list

Task 6: Seed Database (15 minutes)

  1. Create and run CategorySeeder
  2. Verify data in database

📦 Deliverables

By end of day:

  1. Functional Database Schema:
    • All tables created and verified
    • Foreign keys properly configured
    • Test data seeded
  2. Complete Models:
    • All models created with relationships
    • Helper methods implemented
  3. Working Controllers:
    • BookController with full CRUD
    • Other controllers scaffolded
  4. Routes Configured:
    • All routes defined
    • Authentication middleware applied
💡 Pro Tips: