📅 Week 15 - Day 2: Eloquent CRUD Operations

Tuesday | Duration: 3 hours | Master Database Operations! 💾

🎯 Learning Objectives

➕ CREATE - Inserting Data

Method 1: Create and Save

<?php use App\Models\Student; // Create new instance $student = new Student(); $student->name = "Ahmad Ibrahim"; $student->email = "ahmad@example.com"; $student->phone = "08012345678"; $student->age = 20; $student->course = "Web Development"; $student->save(); // Save to database echo "Student created with ID: " . $student->id; ?>

Method 2: Mass Assignment with create()

<?php use App\Models\Student; $student = Student::create([ 'name' => 'Fatima Yusuf', 'email' => 'fatima@example.com', 'phone' => '08098765432', 'age' => 19, 'course' => 'Data Science' ]); echo "Created student: " . $student->name; ?>

Important: For create() to work, fields must be listed in the model's $fillable property!

Model Configuration for Mass Assignment:

<?php // app/Models/Student.php class Student extends Model { protected $fillable = [ 'name', 'email', 'phone', 'age', 'course' ]; } ?>

📖 READ - Retrieving Data

Get All Records:

<?php use App\Models\Student; // Get all students $students = Student::all(); foreach ($students as $student) { echo $student->name . " - " . $student->email . "<br>"; } ?>

Get Single Record by ID:

<?php // Find by primary key $student = Student::find(1); if ($student) { echo "Name: " . $student->name; } else { echo "Student not found!"; } // Find or fail (throws 404 if not found) $student = Student::findOrFail(1); ?>

Query with Where Conditions:

<?php // Get students by course $webDevStudents = Student::where('course', 'Web Development')->get(); // Multiple conditions $adults = Student::where('age', '>=', 18) ->where('course', 'Web Development') ->get(); // OR condition $students = Student::where('course', 'Web Development') ->orWhere('course', 'Data Science') ->get(); // Get first match $student = Student::where('email', 'ahmad@example.com')->first(); ?>

Useful Query Methods:

Method Description Example
all() Get all records Student::all()
find($id) Find by primary key Student::find(5)
first() Get first record Student::first()
where() Add where condition where('age', '>', 18)
orderBy() Sort results orderBy('name', 'asc')
limit() Limit results limit(10)
count() Count records Student::count()

✏️ UPDATE - Modifying Data

Method 1: Find and Save

<?php use App\Models\Student; // Find student $student = Student::find(1); // Update properties $student->name = "Ahmad Ibrahim Updated"; $student->age = 21; // Save changes $student->save(); echo "Student updated!"; ?>

Method 2: Direct Update with where()

<?php // Update all students in Web Development course Student::where('course', 'Web Development') ->update(['age' => 20]); // Update single record Student::where('id', 1) ->update([ 'name' => 'New Name', 'email' => 'newemail@example.com' ]); ?>

Method 3: updateOrCreate()

<?php // Update if exists, create if doesn't Student::updateOrCreate( ['email' => 'ahmad@example.com'], // Search criteria [ 'name' => 'Ahmad Ibrahim', 'phone' => '08012345678', 'age' => 20, 'course' => 'Web Development' ] ); ?>

🗑️ DELETE - Removing Data

Method 1: Find and Delete

<?php use App\Models\Student; $student = Student::find(1); if ($student) { $student->delete(); echo "Student deleted!"; } ?>

Method 2: Delete by ID

<?php // Delete single record Student::destroy(1); // Delete multiple records Student::destroy([1, 2, 3]); // Delete with where condition Student::where('age', '<', 18)->delete(); ?>

💻 Complete CRUD Controller Example

Create Controller:

php artisan make:controller StudentController --resource

Controller with Full CRUD:

<?php // app/Http/Controllers/StudentController.php namespace App\Http\Controllers; use App\Models\Student; use Illuminate\Http\Request; class StudentController extends Controller { // Display all students public function index() { $students = Student::orderBy('name', 'asc')->get(); return view('students.index', compact('students')); } // Show create form public function create() { return view('students.create'); } // Store new student public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|min:3|max:50', 'email' => 'required|email|unique:students', 'phone' => 'required', 'age' => 'required|numeric|min:16', 'course' => 'required' ]); Student::create($validated); return redirect('/students')->with('success', 'Student added successfully!'); } // Show single student public function show($id) { $student = Student::findOrFail($id); return view('students.show', compact('student')); } // Show edit form public function edit($id) { $student = Student::findOrFail($id); return view('students.edit', compact('student')); } // Update student public function update(Request $request, $id) { $student = Student::findOrFail($id); $validated = $request->validate([ 'name' => 'required|min:3|max:50', 'email' => 'required|email|unique:students,email,' . $id, 'phone' => 'required', 'age' => 'required|numeric|min:16', 'course' => 'required' ]); $student->update($validated); return redirect('/students')->with('success', 'Student updated!'); } // Delete student public function destroy($id) { $student = Student::findOrFail($id); $student->delete(); return redirect('/students')->with('success', 'Student deleted!'); } } ?>

Routes for CRUD:

<?php // routes/web.php use App\Http\Controllers\StudentController; // Resource route creates all CRUD routes Route::resource('students', StudentController::class); // This creates: // GET /students -> index() // GET /students/create -> create() // POST /students -> store() // GET /students/{id} -> show() // GET /students/{id}/edit -> edit() // PUT /students/{id} -> update() // DELETE /students/{id} -> destroy() ?>

📊 Counting and Aggregates

<?php // Count all students $totalStudents = Student::count(); // Count with condition $webDevCount = Student::where('course', 'Web Development')->count(); // Average age $avgAge = Student::avg('age'); // Maximum age $maxAge = Student::max('age'); // Minimum age $minAge = Student::min('age'); // Sum (if you had a numeric column like fees) $totalFees = Student::sum('fees'); ?>

🔍 Advanced Queries

<?php // Order by multiple columns $students = Student::orderBy('course', 'asc') ->orderBy('name', 'asc') ->get(); // Pagination $students = Student::paginate(10); // 10 per page // Select specific columns $students = Student::select('name', 'email')->get(); // Get latest/oldest $latest = Student::latest()->first(); // Most recent $oldest = Student::oldest()->first(); // Oldest // Check if exists $exists = Student::where('email', 'test@example.com')->exists(); // Pluck (get array of column values) $names = Student::pluck('name'); // ['Ahmad', 'Fatima', ...] $emailMap = Student::pluck('email', 'id'); // [1 => 'email1', 2 => 'email2'] ?>

✏️ Practice Exercises

  1. Create 5 students using both save() and create() methods
  2. Retrieve all students and display in a table
  3. Find students older than 18 years
  4. Update a student's course and age
  5. Delete a student by ID
  6. Count total students in each course
  7. Create a complete CRUD system for Products

✅ Today's Deliverable

← Previous Course Home Next →