Conditional statements in PHP enable you to check whether or not a condition is true in the code. If the condition is true, the code will be executed otherwise it will not be executed.
First of all, we are going to see how the “if statement” works in Laravel. It is actually very easy to construct if statements in Laravel. You have to use @if, @else and @elseif directives to construct if statement, else statement and elseif statement respectively. Similarly, the @endif directive will end the if statement for you.
The following is the syntax of each of these types of loops. Once again, remember that these structures work identically to their PHP counterparts.
@if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif
There is also an @unless directive in Laravel Blade. The @unless directive prevents the browser to perform a certain task, such as a person trying to access information on a website, unless he is signed in. Here is how you can use this directive.
@unless (Auth::check()) You are not signed in. @endunless
The Blade also provides directives like @empty and @isset in addition to the @unless directive. You can use these directives as easy shortcuts for respective PHP functions.
@isset($records) // $records is defined and is not null... @endisset @empty($records) // $records is "empty"... @endempty
You can also take help from a very useful directive called @hasSection to check whether or not a section has content.
@hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"></div> @endif
When it comes to switch statements, you can construct them using directives like @switch, @default, @break, and at the @case. Here is thy syntax of all types of switch statements in Laravel.
@switch($i) @case(1) First case... @break @case(2) Second case... @break @default Default case... @endswitch
In the next lesson, we are going to study the Custom Helper Function in Laravel.