📅 Week 14 - Day 1: Blade Templates & Syntax

Monday | Duration: 3 hours | Master Laravel's Template Engine! 🎨

🎯 Learning Objectives

🌟 What is Blade?

Blade is Laravel's powerful templating engine. It allows you to write clean, readable templates with PHP logic while maintaining separation of concerns.

File Extension: .blade.php (stored in resources/views/)

📝 Displaying Data

Basic Echo Syntax:

<!-- Blade escapes HTML automatically (secure) --> <h1>Hello, {{ $name }}!</h1> <!-- Display unescaped HTML (use carefully!) --> <div>{!! $htmlContent !!}</div> <!-- Display if variable exists, otherwise default --> <p>{{ $message ?? 'No message available' }}</p>

Controller Example:

<?php // app/Http/Controllers/PageController.php public function index() { $name = "Ahmad Ibrahim"; $age = 20; $course = "Web Development"; return view('welcome', compact('name', 'age', 'course')); } ?>

View Example:

<!-- resources/views/welcome.blade.php --> <!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome, {{ $name }}!</h1> <p>You are {{ $age }} years old.</p> <p>Enrolled in: {{ $course }}</p> </body> </html>

🔀 Conditional Statements

@if, @elseif, @else:

<!-- Check conditions --> @if($score >= 80) <p style="color: green;">Excellent! Grade: A</p> @elseif($score >= 70) <p style="color: blue;">Good! Grade: B</p> @elseif($score >= 60) <p style="color: orange;">Average! Grade: C</p> @else <p style="color: red;">Failed! Grade: F</p> @endif

@unless (opposite of @if):

@unless($user->isAdmin) <p>You don't have admin privileges.</p> @endunless

@isset, @empty:

@isset($name) <p>Name is set: {{ $name }}</p> @endisset @empty($records) <p>No records found!</p> @endempty

🔁 Loops

@foreach Loop:

<!-- Controller --> <?php $students = [ ['name' => 'Ahmad', 'age' => 20], ['name' => 'Fatima', 'age' => 19], ['name' => 'Ibrahim', 'age' => 21], ]; return view('students', compact('students')); ?> <!-- View --> <h2>Students List</h2> <ul> @foreach($students as $student) <li>{{ $student['name'] }} - Age: {{ $student['age'] }}</li> @endforeach </ul> <!-- Display message if empty --> @forelse($students as $student) <li>{{ $student['name'] }}</li> @empty <p>No students found.</p> @endforelse

@for Loop:

<h3>Numbers 1 to 10:</h3> <ul> @for($i = 1; $i <= 10; $i++) <li>Number {{ $i }}</li> @endfor </ul>

@while Loop:

@php $count = 1; @endphp @while($count <= 5) <p>Count: {{ $count }}</p> @php $count++; @endphp @endwhile

$loop Variable (available in loops):

@foreach($students as $student) <p> @if($loop->first) <strong>First:</strong> @endif {{ $student['name'] }} @if($loop->last) <strong>(Last)</strong> @endif <!-- Iteration: {{ $loop->iteration }} / {{ $loop->count }} --> </p> @endforeach

📋 Blade Directives Reference

Directive Purpose Example
{{ }} Echo data (escaped) {{ $name }}
{!! !!} Echo raw HTML {!! $html !!}
@if / @endif Conditional @if($age > 18) Adult @endif
@foreach / @endforeach Loop array @foreach($items as $item) ... @endforeach
@for / @endfor For loop @for($i=0; $i<10; $i++) ... @endfor
@php / @endphp Raw PHP code @php $x = 10; @endphp
{{-- comment --}} Blade comment {{-- This won't show --}}

💻 Complete Example: Student Report Card

Controller:

<?php // app/Http/Controllers/ReportController.php namespace App\Http\Controllers; class ReportController extends Controller { public function show() { $student = [ 'name' => 'Ahmad Ibrahim', 'id' => 'STD001', 'class' => '10th Grade' ]; $subjects = [ ['name' => 'Mathematics', 'score' => 85], ['name' => 'English', 'score' => 78], ['name' => 'Science', 'score' => 92], ['name' => 'History', 'score' => 70], ['name' => 'Computer', 'score' => 88], ]; return view('report-card', compact('student', 'subjects')); } } ?>

Route:

<?php // routes/web.php use App\Http\Controllers\ReportController; Route::get('/report', [ReportController::class, 'show']); ?>

View (resources/views/report-card.blade.php):

<!DOCTYPE html> <html> <head> <title>Report Card</title> <style> body { font-family: Arial; max-width: 600px; margin: 50px auto; } h1 { color: #fcb69f; text-align: center; } .info { background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0; } table { width: 100%; border-collapse: collapse; margin: 20px 0; } th, td { padding: 12px; text-align: left; border: 1px solid #ddd; } th { background: #fcb69f; color: white; } .grade-a { color: green; font-weight: bold; } .grade-b { color: blue; } .grade-c { color: orange; } .grade-f { color: red; } </style> </head> <body> <h1>Report Card</h1> <div class="info"> <p><strong>Name:</strong> {{ $student['name'] }}</p> <p><strong>Student ID:</strong> {{ $student['id'] }}</p> <p><strong>Class:</strong> {{ $student['class'] }}</p> </div> <h2>Subjects & Scores</h2> <table> <thead> <tr> <th>#</th> <th>Subject</th> <th>Score</th> <th>Grade</th> <th>Status</th> </tr> </thead> <tbody> @php $totalScore = 0; @endphp @foreach($subjects as $subject) @php $totalScore += $subject['score']; // Calculate grade if($subject['score'] >= 80) { $grade = 'A'; $gradeClass = 'grade-a'; } elseif($subject['score'] >= 70) { $grade = 'B'; $gradeClass = 'grade-b'; } elseif($subject['score'] >= 60) { $grade = 'C'; $gradeClass = 'grade-c'; } else { $grade = 'F'; $gradeClass = 'grade-f'; } @endphp <tr> <td>{{ $loop->iteration }}</td> <td>{{ $subject['name'] }}</td> <td>{{ $subject['score'] }}</td> <td class="{{ $gradeClass }}">{{ $grade }}</td> <td> @if($subject['score'] >= 60) ✅ Pass @else ❌ Fail @endif </td> </tr> @endforeach </tbody> </table> @php $average = $totalScore / count($subjects); @endphp <div class="info"> <h3>Summary</h3> <p><strong>Total Subjects:</strong> {{ count($subjects) }}</p> <p><strong>Total Score:</strong> {{ $totalScore }} / {{ count($subjects) * 100 }}</p> <p><strong>Average:</strong> {{ number_format($average, 2) }}%</p> @if($average >= 80) <p style="color: green;"><strong>Overall Grade: A (Excellent!)</strong></p> @elseif($average >= 70) <p style="color: blue;"><strong>Overall Grade: B (Good)</strong></p> @elseif($average >= 60) <p style="color: orange;"><strong>Overall Grade: C (Average)</strong></p> @else <p style="color: red;"><strong>Overall Grade: F (Needs Improvement)</strong></p> @endif </div> </body> </html>

✏️ Practice Exercises

  1. Create a product listing page using @foreach
  2. Build a grade calculator with @if conditions
  3. Display odd/even numbers using @for and @if
  4. Create a shopping cart with @forelse (show message if empty)
  5. Use $loop variable to add alternating row colors
  6. Convert one of your previous HTML pages to Blade template

✅ Today's Deliverable

← Previous Course Home Next →