How to Use Ternary Operator in Blade Templates
In Blade templates, use the ternary operator with the syntax
{{ condition ? true_value : false_value }} to display content based on a condition. This lets you write simple if-else logic inline within your HTML.Syntax
The ternary operator in Blade follows this pattern:
condition: A boolean expression to check.true_value: The value or content shown if the condition is true.false_value: The value or content shown if the condition is false.
It is wrapped inside Blade's curly braces {{ }} to output the result.
php
{{ condition ? true_value : false_value }}Example
This example shows how to display "Logged In" if the user is authenticated, or "Guest" if not.
blade
@php $isLoggedIn = true; @endphp <p>Status: {{ $isLoggedIn ? 'Logged In' : 'Guest' }}</p>
Output
<p>Status: Logged In</p>
Common Pitfalls
Common mistakes include:
- Forgetting to wrap the ternary expression inside
{{ }}, so it won't output. - Using PHP tags
inside Blade unnecessarily. - Not ensuring the condition is a boolean expression.
Always keep the ternary inside Blade's curly braces for output.
blade
@php $isAdmin = false; @endphp <!-- Wrong: missing curly braces, no output --> <p>Status: $isAdmin ? 'Admin' : 'User'</p> <!-- Right: wrapped in curly braces --> <p>Status: {{ $isAdmin ? 'Admin' : 'User' }}</p>
Output
<p>Status: User</p>
Quick Reference
Use ternary in Blade for simple inline conditions to keep templates clean and readable.
- Wrap expression in
{{ }}. - Use
condition ? true_value : false_valuesyntax. - Use for short if-else logic only.
Key Takeaways
Use the ternary operator inside Blade's {{ }} to output conditional content.
The syntax is: condition ? true_value : false_value.
Always ensure the condition is a boolean expression.
Avoid mixing raw PHP tags inside Blade for ternary expressions.
Use ternary for simple inline conditions to keep templates clean.