📘 Laravel Blade Templating
Blade is Laravel’s simple yet powerful templating engine that allows you to write clean, reusable, and dynamic views using expressive syntax.
📁 Location of Blade Files
resources/views/
Blade files use the extension: .blade.php
✅ Displaying Data
{{ '{{ $name }}' }} // Escaped output {!! '{!! $htmlContent !!}' !!} // Unescaped output
📄 Blade Directives
Conditional Directives
@if ($age > 18) You are an adult. @elseif ($age == 18) Just turned adult. @else You are a minor. @endif
Loop Directives
@for ($i = 0; $i < 5; $i++) {{ '{{ $i }}' }} @endfor @foreach ($users as $user) {{ '{{ $user->name }}' }} @endforeach @forelse ($tasks as $task) {{ '{{ $task }}' }} @empty No tasks @endforelse @while ($i < 10) {{ '{{ $i++ }}' }} @endwhile
🔁 Include Other Views
@include('partials.header')
🧱 Layouts and Sections
Create a Layout
<!DOCTYPE html> <html> <head> <title>@yield('title')</title> </head> <body> @include('partials.navbar') <div class="container"> @yield('content') </div> </body> </html>
Use Layout in Child Views
@extends('layout') @section('title', 'Home Page') @section('content') <h1>Welcome to Laravel</h1> @endsection
🔧 Components
<x-alert type="danger" message="Error occurred!" />
Defined in: resources/views/components/alert.blade.php
<div class="alert alert-{{ '{{ $type }}' }}"> {{ '{{ $message }}' }} </div>
📥 Passing Data to Views
return view('home', ['name' => 'John']);
<p>Hello, {{ '{{ $name }}' }}</p>
🔐 CSRF Protection
<form method="POST" action="/submit"> @csrf <input type="text" name="data"> </form>
🧭 Route URL and Asset Helpers
<a href="{{ '{{ route('home') }}' }}">Home</a> <img src="{{ '{{ asset('images/logo.png') }}' }}" alt="Logo">
🎮 Switch Statement
@switch($role) @case('admin') Admin Panel @break @case('user') User Dashboard @break @default Guest @endswitch
💡 Blade Comments
{{-- This is a Blade comment --}}
📘 Summary Table
Feature | Syntax |
---|---|
Escaped Output | {{ '{{ $var }}' }} |
Unescaped Output | {!! '{!! $html !!}' !!} |
If-Else | @if, @elseif, @else, @endif |
Loops | @foreach, @for, @while, @forelse |
Layouts | @extends, @section, @yield |
Include | @include('view') |
CSRF Token | @csrf |
URL Helpers | route(), asset() |
Comments | {{-- comment --}} |
0 Comments