In Laravel's Blade templating engine, you can use conditional statements to conditionally render content based on certain conditions. Blade provides several directives for handling conditional logic. Here are some common conditional directives:
The @if
directive is used to conditionally display content if a certain condition is true:
@if ($condition)
// Content to display if the condition is true
@endif
The @else
directive is used in conjunction with @if
to display content when the condition is false:
@if ($condition)
// Content to display if the condition is true
@else
// Content to display if the condition is false
@endif
The @elseif
directive allows you to specify additional conditions to check if the initial @if
condition is false:
@if ($condition1)
// Content to display if condition1 is true
@elseif ($condition2)
// Content to display if condition2 is true and condition1 is false
@else
// Content to display if both condition1 and condition2 are false
@endif
The @unless
directive is the opposite of @if
. It displays content unless a certain condition is true:
@unless ($condition)
// Content to display if the condition is false
@endunless
@if ($user->isAdmin())
<p>Welcome, Admin!</p>
@else
<p>Welcome, User!</p>
@endif
In this example, if the isAdmin()
method of the $user
object returns true
, it will display "Welcome, Admin!". Otherwise, it will display "Welcome, User!".
The @isset
directive checks if a variable is set and not null, while @empty
checks if a variable is empty:
@isset($variable)
// $variable is set and not null
@endisset
@empty($variable)
// $variable is empty
@endempty
The @switch
directive is used to perform a multi-way switch statement:
@switch($variable)
@case('value1')
// Content to display if $variable equals 'value1'
@break
@case('value2')
// Content to display if $variable equals 'value2'
@break
@default
// Content to display if $variable doesn't match any cases
@endswitch
You can use the ternary operator inside Blade directives:
{{ $variable ? 'True' : 'False' }}
You can use logical operators like &&
, ||
, !
within Blade directives for more complex conditions.
@if ($user->isAdmin() && $user->isVerified())
// Content to display if the user is both an admin and verified
@endif
These are some of the common conditional directives and techniques in Laravel's Blade templating engine. They provide powerful tools for building dynamic and interactive views in your Laravel applications.