Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogCoursesPhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • Courses
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 14 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Mastering Blade Directives for Loops and Conditionals

Learn how to use Blade directives like @if, @foreach, and @forelse to control your view logic and render dynamic lists in your Laravel applications efficiently.

LaravelBladePHPWeb DevelopmentTemplatingbackend

Previously in this course, we explored Implementing Blade Partials: A Guide to DRY Laravel Views to keep our templates clean and reusable. Now that we have the structural basics down, it's time to make our views truly dynamic.

In any real-world application, you rarely display static content. You need to show "active" tasks, hide buttons for unauthenticated users, or render a list of items from a database. Blade makes this easy by providing a clean, readable syntax for common PHP control structures.

Controlling View Logic with Blade Conditionals

At its core, a view is just a representation of state. Sometimes, you only want to show specific parts of that state if certain conditions are met. Instead of writing raw PHP like <?php if ($task->completed): ?>, Blade gives us the @if directive.

The syntax is expressive and mirrors standard PHP, but without the messy curly braces and closing tags.

BLADE
@if ($task->is_completed)
    <span class="badge">Finished</span>
@elseif ($task->is_urgent)
    <span class="badge badge-warning">Urgent</span>
@else
    <span class="badge badge-info">Pending</span>
@endif

Why use Blade directives?

  1. Readability: Your templates stay clean and look more like HTML than code.
  2. Safety: Blade automatically handles common PHP pitfalls and keeps your syntax consistent.
  3. Integration: Directives are purpose-built to work with the data you pass from your controllers.

Rendering Lists with Loops

When building our Task Manager, the most common task you'll perform is iterating over an array or collection of items. Blade provides the @foreach directive for this exact purpose.

The @foreach Directive

If you have an array of tasks passed from your controller, you can loop through them like this:

BLADE
<ul>
    @foreach ($tasks as $task)
        <li>{{ $task->title }}</li>
    @endforeach
</ul>

The @forelse Directive

One of the most common "gotchas" in development is rendering an empty list. You might show an empty <ul> tag, which looks broken. Laravel provides the @forelse directive to handle this scenario gracefully in one block.

BLADE
<ul>
    @forelse ($tasks as $task)
        <li>{{ $task->title }}</li>
    @empty
        <p>No tasks found. Time to relax!</p>
    @endforelse
</ul>

The @forelse directive checks if the collection is empty. If it is, it automatically jumps to the @empty block. It’s cleaner and more robust than writing an @if check followed by a @foreach.

Hands-on Exercise: Building the Task List

Let’s apply this to our Task Manager. Open your resources/views/tasks/index.blade.php file. Assume your controller is passing a variable named $tasks to this view.

  1. Replace your static list items with a @forelse loop.
  2. Inside the loop, add an @if condition to style the task differently if it's marked as "urgent".
  3. Use the @empty directive to display a friendly message when there are no tasks.
BLADE
<h1>My Tasks</h1>

@forelse ($tasks as $task)
    <div class="{{ $task->urgent ? 'border-red' : 'border-gray' }}">
        <h3>{{ $task->title }}</h3>
        @if ($task->completed)
            <p>Status: Done</p>
        @else
            <p>Status: In Progress</p>
        @endif
    </div>
@empty
    <p>You have no tasks! Enjoy your day.</p>
@endforelse

Common Pitfalls

  • Forgetting the End Directive: Every Blade directive like @if or @foreach must be closed with an @endif or @endforeach. If you forget, you'll see a syntax error in your browser.
  • Variable Scope: Remember that variables defined inside a loop are only available within that loop. Don't try to access $task outside of your @foreach block.
  • Mixing Logic: While Blade is powerful, keep your complex business logic in your Controllers or Models, as discussed in Introduction to Blade: Mastering Laravel's Templating Engine. Keep your views focused on displaying data, not calculating it.

Recap

We’ve moved from static HTML to dynamic templates. By mastering these Blade directives:

  • You use @if, @elseif, and @else to handle conditional UI states.
  • You use @foreach to iterate over data collections.
  • You use @forelse to elegantly handle empty states, ensuring your users never see a blank, confusing page.

These tools are the bread and butter of Laravel development. Once these become muscle memory, building complex interfaces becomes significantly faster.

Up next: We will combine everything we've learned to finalize the Task Manager: Building the User Interface.

Previous lessonImplementing Blade PartialsNext lesson Task Manager: Building the User Interface
Back to Blog

Similar Posts

LaravelJune 25, 20263 min read

Introduction to Blade: Mastering Laravel's Templating Engine

Learn how to use Blade to render dynamic data in Laravel. Discover how to create .blade.php files, use echo syntax, and implement essential directives.

Read more
LaravelJune 25, 20263 min read

Customizing Validation Error Messages for Better Laravel UX

Learn to customize Laravel validation error messages to provide clear, helpful feedback to your users. Master field-specific errors and language files.

Part of the course

Laravel Fundamentals: From Zero to Your First App

beginner · Lesson 14 of 52

  1. 1

    Setting Up the Local Development Environment

    4 min
  2. 2

    Installing Laravel and Exploring Directory Structure

    3 min
  3. 3

    Understanding the .env File and Configuration

    3 min
Read more
LaravelJune 25, 20264 min read

Implementing Blade Partials: A Guide to DRY Laravel Views

Stop repeating yourself in Blade templates. Learn how to implement Blade partials to extract common UI elements and keep your Laravel views maintainable.

Read more
  • 4

    The Laravel Application Lifecycle

    4 min
  • 5

    Initializing the Task Manager Project

    3 min
  • 6

    Defining Basic Web Routes

    4 min
  • 7

    Using Route Parameters

    3 min
  • 8

    Creating Your First Controller

    3 min
  • 9

    Returning Responses and Redirects

    3 min
  • 10

    Task Manager: Implementing the Task List Route

    3 min
  • 11

    Introduction to Blade Templating

    3 min
  • 12

    Using Blade Layouts and Sections

    3 min
  • 13

    Implementing Blade Partials

    4 min
  • 14

    Mastering Blade Directives for Loops and Conditionals

    3 min
  • 15

    Task Manager: Building the User Interface

    3 min
  • 16

    Understanding Database Migrations

    3 min
  • 17

    Working with Eloquent Models

    3 min
  • 18

    Performing Basic CRUD Operations

    3 min
  • 19

    Seeding the Database

    3 min
  • 20

    Task Manager: Displaying Real Database Records

    3 min
  • 21

    Capturing User Input from Forms

    4 min
  • 22

    Introduction to Laravel Validation

    3 min
  • 23

    Customizing Validation Error Messages

    3 min
  • 24

    Using Form Requests for Validation

    3 min
  • 25

    Introduction to Authentication

    4 min
  • 26

    Protecting Routes with Middleware

    Coming soon
  • 27

    Understanding CSRF Protection

    Coming soon
  • 28

    Preventing Mass Assignment

    Coming soon
  • 29

    Task Manager: Securing the Application

    Coming soon
  • 30

    Introduction to Route Model Binding

    Coming soon
  • 31

    Updating Existing Records

    Coming soon
  • 32

    Deleting Records

    Coming soon
  • 33

    Using Named Routes

    Coming soon
  • 34

    Task Manager: Completing CRUD Functionality

    Coming soon
  • 35

    Introduction to Database Relationships

    Coming soon
  • 36

    Querying Related Data

    Coming soon
  • 37

    Handling File Uploads

    Coming soon
  • 38

    Using Flash Messages for User Feedback

    Coming soon
  • 39

    Task Manager: Adding Status and Priorities

    Coming soon
  • 40

    Introduction to Artisan Commands

    Coming soon
  • 41

    Debugging with Laravel Tinker

    Coming soon
  • 42

    Understanding Service Providers

    Coming soon
  • 43

    Using View Composers

    Coming soon
  • 44

    Task Manager: Refactoring for Clean Code

    Coming soon
  • 45

    Introduction to Testing

    Coming soon
  • 46

    Testing Forms and Validation

    Coming soon
  • 47

    Using Database Transactions

    Coming soon
  • 48

    Handling Global Exceptions

    Coming soon
  • 49

    Preparing for Production

    Coming soon
  • 50

    Environment Security Best Practices

    Coming soon
  • 51

    Managing Assets in Production

    Coming soon
  • 52

    Task Manager: Deployment Preparation

    Coming soon
  • View full course