Lesson 5 – Laravel Conditional Statements

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!
    I don't have any records!

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.

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.

    // $records is defined and is not null...

    // $records is "empty"...

You can also take help from a very useful directive called @hasSection to check whether or not a section has content.

    <div class="pull-right">

    <div class="clearfix"></div>

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.

        First case...

        Second case...

        Default case...

In the next lesson, we are going to study the Custom Helper Function in Laravel.

Lesson 3 – Laravel Views