Labs ICT
Pro Login

Blade Directives

@if, @foreach, @unless, and more.

Conditional Statements

Blade makes conditional logic clean and readable. The @if directive works exactly like PHP's if, but reads better in templates:


@if ($score >= 90)
    <p>Grade: A</p>
@elseif ($score >= 80)
    <p>Grade: B</p>
@else
    <p>Grade: C</p>
@endif
    

You can also use @unless, which is the opposite of @if:


@unless ($user->isAdmin())
    <p>You are not an admin.</p>
@endunless
    
Try it Yourself →

Loops

Blade provides @for, @foreach, and @while for iteration. The @foreach loop is the most commonly used:


@foreach ($users as $user)
    <p>{{ $user->name }}</p>
@endforeach
    

Inside a loop, you have access to special variables like $loop->index, $loop->first, and $loop->last:


@foreach ($items as $item)
    @if ($loop->first)
        <p>First item:</p>
    @endif
    <p>{{ $item->name }}</p>
@endforeach
    

Checking Existence with @isset and @empty

Quick checks for null values or empty collections:


@isset($user)
    <p>{{ $user->name }}</p>
@endisset

@empty($items)
    <p>No items found.</p>
@endempty
    

Authentication Directives

Blade has built-in directives for authentication checks. @auth checks if the user is logged in, and @guest checks the opposite:


@auth
    <a href="/dashboard">Dashboard</a>
@endauth

@guest
    <a href="/login">Login</a>
@endguest
    

You can also specify a guard:


@auth('admin')
    <p>Admin panel</p>
@endauth
    

Custom Directives

You can create your own Blade directives using Blade::directive in a service provider. This lets you add custom syntax that compiles to PHP code:


Blade::directive('datetime', function ($expression) {
    return "<?php echo \\Carbon\\Carbon::parse($expression)->diffForHumans(); ?>";
});
    

Now you can use @datetime($post->created_at) in your templates.