0
0
Laravelframework~5 mins

Control structures (@if, @foreach, @for) in Laravel

Choose your learning style9 modes available
Introduction

Control structures help you decide what to show or repeat in your web pages. They make your templates smart and dynamic.

Show a message only if a user is logged in.
List all items in a shopping cart.
Repeat a block of HTML a fixed number of times.
Display different content based on a condition.
Syntax
Laravel
@if (condition)
    // code to show if true
@elseif (another_condition)
    // code to show if elseif true
@else
    // code to show if all false
@endif

@foreach ($items as $item)
    // code to repeat for each item
@endforeach

@for ($i = 0; $i < 5; $i++)
    // code to repeat 5 times
@endfor

Use @if to check conditions and show content accordingly.

@foreach loops over each item in a list.

@for repeats code a set number of times.

Examples
Shows a message depending on whether the user is an admin.
Laravel
@if ($user->isAdmin())
    <p>Welcome, admin!</p>
@else
    <p>Welcome, guest!</p>
@endif
Lists all product names in a list.
Laravel
@foreach ($products as $product)
    <li>{{ $product->name }}</li>
@endforeach
Repeats a paragraph showing numbers 1 to 3.
Laravel
@for ($i = 1; $i <= 3; $i++)
    <p>Number {{ $i }}</p>
@endfor
Sample Program

This example shows how to use @if to greet an admin user, @foreach to list tasks, and @for to count down from 3.

Laravel
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Control Structures Example</title>
</head>
<body>
    @php
        $user = (object) ['name' => 'Alice', 'isAdmin' => function() { return true; }];
        $tasks = ['Buy milk', 'Write code', 'Read book'];
    @endphp

    @if ($user->isAdmin())
        <h1>Welcome, Admin {{ $user->name }}!</h1>
    @else
        <h1>Welcome, Guest!</h1>
    @endif

    <h2>Your Tasks:</h2>
    <ul>
        @foreach ($tasks as $task)
            <li>{{ $task }}</li>
        @endforeach
    </ul>

    <h2>Countdown:</h2>
    @for ($i = 3; $i > 0; $i--)
        <p>{{ $i }}</p>
    @endfor
</body>
</html>
OutputSuccess
Important Notes

Always close control structures with @endif, @endforeach, or @endfor.

You can nest these structures inside each other for more complex logic.

Use Blade's double curly braces {{ }} to safely display variables.

Summary

@if lets you show content based on conditions.

@foreach repeats content for each item in a list.

@for repeats content a set number of times.