⚙️ Week 20, Day 2: Authentication & CRUD Implementation

Build Complete Task Management Features

📖 Learning Objectives

🗄️ Database Migrations

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->string('color', 7)->default('#3b82f6'); $table->timestamps(); }); }

2. Tasks Migration:

// database/migrations/xxxx_create_tasks_table.php public function up() { Schema::create('tasks', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->foreignId('category_id')->constrained()->onDelete('cascade'); $table->string('title'); $table->text('description')->nullable(); $table->enum('status', ['pending', 'in_progress', 'completed']) ->default('pending'); $table->enum('priority', ['low', 'medium', 'high'])->default('medium'); $table->date('due_date')->nullable(); $table->timestamp('completed_at')->nullable(); $table->timestamps(); }); }

3. Attachments Migration:

// database/migrations/xxxx_create_attachments_table.php public function up() { Schema::create('attachments', function (Blueprint $table) { $table->id(); $table->foreignId('task_id')->constrained()->onDelete('cascade'); $table->string('file_name'); $table->string('file_path'); $table->integer('file_size'); $table->string('mime_type'); $table->timestamps(); }); } // Run migrations php artisan migrate

📦 Eloquent Models

1. Category Model:

// app/Models/Category.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Category extends Model { protected $fillable = ['name', 'color']; // Relationship: Category has many tasks public function tasks() { return $this->hasMany(Task::class); } }

2. Task Model:

// app/Models/Task.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = [ 'user_id', 'category_id', 'title', 'description', 'status', 'priority', 'due_date', 'completed_at' ]; protected $casts = [ 'due_date' => 'date', 'completed_at' => 'datetime', ]; // Relationship: Task belongs to user public function user() { return $this->belongsTo(User::class); } // Relationship: Task belongs to category public function category() { return $this->belongsTo(Category::class); } // Relationship: Task has many attachments public function attachments() { return $this->hasMany(Attachment::class); } }

3. Attachment Model:

// app/Models/Attachment.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Attachment extends Model { protected $fillable = [ 'task_id', 'file_name', 'file_path', 'file_size', 'mime_type' ]; // Relationship: Attachment belongs to task public function task() { return $this->belongsTo(Task::class); } }

🎨 Dashboard Controller

// app/Http/Controllers/DashboardController.php namespace App\Http\Controllers; use App\Models\Task; use Illuminate\Http\Request; class DashboardController extends Controller { public function index() { $user = auth()->user(); // Get task statistics $totalTasks = $user->tasks()->count(); $pendingTasks = $user->tasks()->where('status', 'pending')->count(); $completedTasks = $user->tasks()->where('status', 'completed')->count(); // Get recent tasks $recentTasks = $user->tasks() ->with('category') ->latest() ->take(5) ->get(); return view('dashboard', compact( 'totalTasks', 'pendingTasks', 'completedTasks', 'recentTasks' )); } }

⚙️ Task Controller (CRUD)

Complete TaskController:

// app/Http/Controllers/TaskController.php namespace App\Http\Controllers; use App\Models\Task; use App\Models\Category; use Illuminate\Http\Request; class TaskController extends Controller { // Display all tasks public function index() { $tasks = auth()->user()->tasks() ->with('category') ->latest() ->paginate(10); return view('tasks.index', compact('tasks')); } // Show create form public function create() { $categories = Category::all(); return view('tasks.create', compact('categories')); } // Store new task public function store(Request $request) { $validated = $request->validate([ 'category_id' => 'required|exists:categories,id', 'title' => 'required|string|max:255', 'description' => 'nullable|string', 'priority' => 'required|in:low,medium,high', 'due_date' => 'nullable|date', 'attachment' => 'nullable|file|max:2048', ]); // Create task $task = auth()->user()->tasks()->create($validated); // Handle file upload if ($request->hasFile('attachment')) { $file = $request->file('attachment'); $path = $file->store('attachments', 'public'); $task->attachments()->create([ 'file_name' => $file->getClientOriginalName(), 'file_path' => $path, 'file_size' => $file->getSize(), 'mime_type' => $file->getMimeType(), ]); } return redirect()->route('tasks.index') ->with('success', 'Task created successfully!'); } // Show single task public function show(Task $task) { // Authorize: only owner can view if ($task->user_id !== auth()->id()) { abort(403); } $task->load('category', 'attachments'); return view('tasks.show', compact('task')); } // Show edit form public function edit(Task $task) { if ($task->user_id !== auth()->id()) { abort(403); } $categories = Category::all(); return view('tasks.edit', compact('task', 'categories')); } // Update task public function update(Request $request, Task $task) { if ($task->user_id !== auth()->id()) { abort(403); } $validated = $request->validate([ 'category_id' => 'required|exists:categories,id', 'title' => 'required|string|max:255', 'description' => 'nullable|string', 'status' => 'required|in:pending,in_progress,completed', 'priority' => 'required|in:low,medium,high', 'due_date' => 'nullable|date', ]); $task->update($validated); return redirect()->route('tasks.show', $task) ->with('success', 'Task updated successfully!'); } // Delete task public function destroy(Task $task) { if ($task->user_id !== auth()->id()) { abort(403); } $task->delete(); return redirect()->route('tasks.index') ->with('success', 'Task deleted successfully!'); } }

🛣️ Routes Configuration

// routes/web.php use App\Http\Controllers\DashboardController; use App\Http\Controllers\TaskController; use App\Http\Controllers\CategoryController; Route::middleware(['auth'])->group(function () { // Dashboard Route::get('/dashboard', [DashboardController::class, 'index']) ->name('dashboard'); // Task CRUD Route::resource('tasks', TaskController::class); // Categories Route::resource('categories', CategoryController::class); });

🌱 Database Seeder

// database/seeders/CategorySeeder.php namespace Database\Seeders; use App\Models\Category; use Illuminate\Database\Seeder; class CategorySeeder extends Seeder { public function run() { $categories = [ ['name' => 'Work', 'color' => '#3b82f6'], ['name' => 'Personal', 'color' => '#10b981'], ['name' => 'Shopping', 'color' => '#f59e0b'], ['name' => 'Health', 'color' => '#ef4444'], ['name' => 'Education', 'color' => '#8b5cf6'], ]; foreach ($categories as $category) { Category::create($category); } } } // Run seeder php artisan db:seed --class=CategorySeeder

✍️ Practice Exercises

Exercise 1: Complete Migrations

  1. Create all three migrations
  2. Define foreign key constraints
  3. Run migrations
  4. Verify tables in phpMyAdmin

Exercise 2: Implement Models

  1. Create all three models
  2. Define relationships
  3. Test relationships in tinker
  4. Seed categories

Exercise 3: Build Task CRUD

  1. Implement TaskController
  2. Create task forms (create/edit)
  3. Add file upload functionality
  4. Test all CRUD operations

🎯 Today's Deliverable

✅ Working Task Management System

Requirements:

  • All migrations created and executed
  • Models with relationships defined
  • Complete task CRUD functionality
  • File attachment feature working
  • Dashboard showing task statistics
  • Categories seeded in database
  • At least 5 test tasks created

📚 Summary

🔜 What's Next?

In Day 3, we'll complete: