How to Use @if in Blade Templates in Laravel
Use the
@if directive in Blade to conditionally show content based on a boolean expression. Wrap the content inside @if(condition) and @endif tags. You can also use @elseif and @else for multiple conditions.Syntax
The @if directive checks a condition and shows the content inside it only if the condition is true. You close it with @endif. You can add @elseif for another condition and @else for the fallback case.
@if(condition): Start conditional block.@elseif(condition): Optional, checks another condition if the first is false.@else: Optional, runs if all above conditions are false.@endif: Ends the conditional block.
php
@if(condition)
// content if condition is true
@elseif(anotherCondition)
// content if anotherCondition is true
@else
// content if none of the above conditions are true
@endifExample
This example shows how to display a greeting message based on the time of day using @if, @elseif, and @else in a Blade template.
php
@php
$hour = date('H');
@endphp
@if($hour < 12)
Good morning!
@elseif($hour < 18)
Good afternoon!
@else
Good evening!
@endifOutput
Good morning! (if before 12pm) or Good afternoon! (if between 12pm and 6pm) or Good evening! (if after 6pm)
Common Pitfalls
Common mistakes when using @if include forgetting to close the block with @endif, using incorrect PHP syntax inside the condition, or mixing Blade directives with raw PHP incorrectly.
Also, avoid putting complex logic inside the @if condition; instead, prepare data in the controller.
php
@if($user->isAdmin())
<p>Welcome, admin!</p>
<!-- Missing @endif here causes an error -->
<!-- Correct usage -->
@if($user->isAdmin())
<p>Welcome, admin!</p>
@endifQuick Reference
| Directive | Description |
|---|---|
| @if(condition) | Starts a conditional block that runs if condition is true |
| @elseif(condition) | Checks another condition if previous @if or @elseif was false |
| @else | Runs if all previous conditions are false |
| @endif | Ends the conditional block |
Key Takeaways
Use @if to conditionally display content in Blade templates based on boolean expressions.
Always close your @if blocks with @endif to avoid errors.
Use @elseif and @else for multiple condition checks and fallback content.
Keep complex logic out of Blade and prepare data in controllers.
Blade directives make your templates clean and easy to read.