SyntaxStudy
Sign Up
Laravel Beginner 1 min read

Blade Templating Basics

Blade is Laravel's lightweight but powerful templating engine. Unlike other PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. All Blade views are compiled into plain PHP and cached, so they add virtually no overhead. Blade view files use the .blade.php extension and are stored in the resources/views directory. Blade's double-curly-brace syntax ({{ $variable }}) outputs data with automatic HTML entity escaping, protecting against XSS attacks. The unescaped syntax ({!! $html !!}) outputs raw HTML and should only be used with trusted content. Control structures like @if, @elseif, @else, @endif, @foreach, @forelse, @while, and @for mirror PHP constructs but are cleaner to read in template files. The @php directive allows running arbitrary PHP within a template, while @dd and @dump provide quick debugging. The $loop variable inside @foreach provides metadata such as the current index ($loop->index), whether it is the first or last iteration ($loop->first, $loop->last), and the iteration count ($loop->count). Nested loops expose parent loop data via $loop->parent.
Example
{{-- resources/views/posts/index.blade.php --}}

@extends('layouts.app')

@section('title', 'All Posts')

@section('content')
    <h1>Posts</h1>

    @if($posts->isEmpty())
        <p>No posts found.</p>
    @else
        @foreach($posts as $post)
            <article class="{{ $loop->even ? 'bg-gray-50' : 'bg-white' }}">
                <h2>
                    <a href="{{ route('posts.show', $post) }}">
                        {{ $post->title }}
                    </a>
                </h2>
                <p>By {{ $post->user->name }}</p>
                <time>{{ $post->published_at->diffForHumans() }}</time>

                @if($loop->last)
                    <hr class="mt-4">
                @endif
            </article>
        @endforeach

        {{ $posts->links() }}
    @endif
@endsection

@push('scripts')
    <script>console.log('Posts page loaded');</script>
@endpush