0
0
LaravelHow-ToBeginner · 4 min read

How to Use Blade Syntax in Laravel Templates

Blade syntax in Laravel uses @directives and double curly braces {{ }} to embed PHP code in templates. You write HTML mixed with Blade tags to display variables, control structures, and include other views easily.
📐

Syntax

Blade syntax uses simple tags to embed PHP logic inside HTML. Use {{ }} to print variables safely, and @ directives for control structures like loops and conditionals.

  • {{ $variable }}: Outputs escaped variable content.
  • {!! $variable !!}: Outputs raw HTML without escaping.
  • @if(condition) ... @endif: Conditional statements.
  • @foreach($items as $item) ... @endforeach: Loop through arrays.
  • @include('view.name'): Include another Blade template.
blade
<!-- Blade syntax example -->
<h1>{{ $title }}</h1>
@if($user)
  <p>Welcome, {{ $user->name }}!</p>
@else
  <p>Please log in.</p>
@endif
<ul>
  @foreach($items as $item)
    <li>{{ $item }}</li>
  @endforeach
</ul>
💻

Example

This example shows a Blade template displaying a title, a greeting if a user is logged in, and a list of items.

blade
<!-- resources/views/example.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blade Example</title>
</head>
<body>
  <h1>{{ $title }}</h1>

  @if($user)
    <p>Welcome, {{ $user->name }}!</p>
  @else
    <p>Please log in.</p>
  @endif

  <ul>
    @foreach($items as $item)
      <li>{{ $item }}</li>
    @endforeach
  </ul>
</body>
</html>
Output
<h1>My Page</h1> <p>Welcome, Alice!</p> <ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul>
⚠️

Common Pitfalls

Common mistakes include forgetting to use {{ }} for output, which causes no visible content, or using raw output {!! !!} without sanitizing, risking security issues. Also, mixing PHP tags <?php ?> inside Blade can confuse the template engine.

Always close directives like @if with @endif and loops with @endforeach.

blade
<!-- Wrong: missing output tags -->
<p>$title</p>

<!-- Right: use Blade output -->
<p>{{ $title }}</p>
📊

Quick Reference

Blade SyntaxDescription
{{ $variable }}Print escaped variable content
{!! $variable !!}Print raw HTML content
@if(condition) ... @endifConditional statements
@foreach($items as $item) ... @endforeachLoop through arrays
@include('view.name')Include another Blade template
@extends('layout')Extend a layout template
@section('name') ... @endsectionDefine a section for layouts
@yield('name')Display a section content

Key Takeaways

Use {{ }} to safely display variables in Blade templates.
Control structures use @if, @foreach, and must be properly closed.
Avoid raw output {!! !!} unless you trust the content to prevent security risks.
Blade templates mix HTML and PHP logic cleanly with simple syntax.
Always close Blade directives to avoid template errors.