Switch in Laravel 5 - Blade
Asked Answered
D

9

100

How can I use switch in blade templates? When I used:

@switch($login_error)
    @case(1)
        `E-mail` input is empty!
        @break
    @case(2)
        `Password` input is empty!
        @break
@endswitch

in result I see this text as plaintext. I prefer to use switch in few piece of code because it's more clean for me than when I using if.

But if it's not possible just write it.

Downtime answered 27/4, 2015 at 13:42 Comment(4)
github.com/laravel/framework/issues/1857Tricostate
@Downtime The selected answer is incorrect. Can the answer be changed to the one I have posted?Barye
@Barye sorry but this solution is for Laravel 5.2+ - we are using 5.1 LTS.Downtime
laravel 5.5 introduces switch statements. your code should render properly.Karat
C
166

Updated 2020 Answer

Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.

@switch($login_error)
    @case(1)
        <span> `E-mail` input is empty!</span>
        @break

    @case(2)
        <span>`Password` input is empty!</span>
        @break

    @default
        <span>Something went wrong, please try again</span>
@endswitch

Older Answer

Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.

Option 1:

@if ($login_error == 1)
    `E-mail` input is empty!
@elseif ($login_error == 2)
    `Password` input is empty!
@endif
Chigger answered 27/4, 2015 at 13:45 Comment(0)
V
30

You can just add these code in AppServiceProvider class boot method.

Blade::extend(function($value, $compiler){
        $value = preg_replace('/(\s*)@switch\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
        $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
        $value = preg_replace('/(\s*)@case\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
        $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
        $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
        return $value;
    });

then you can use as:

@switch( $item )
    @case( condition_1 )
        // do something
    @breakswitch
    @case( condition_2 )
        // do something else
    @breakswitch
    @default
        // do default behaviour
    @breakswitch
@endswitch

Enjoy It~

Valenta answered 24/2, 2016 at 15:36 Comment(7)
This doesn't work. parse error, expecting &quot;endswitch (T_ENDSWITCH)&quot;&#039; or &quot;case (T_CASE)&quot;&#039; or &quot;default (T_DEFAULT)`Nigritude
@mkmnstr, Try to replace ` ' ` to ` " ` in preg_replace method?Valenta
Anyone upvoted since these comments? Does this work?Thickening
Using Laravel 5.4, does not work for me. FatalThrowableError Class 'App\Providers\Blade' not foundCicelycicenia
It does work on 5.5. I would just be curious on how to get it to work with phpstorm autocompletion (or any IDE) @Valenta ?Myelencephalon
As per @baders answer, this is now supported natively in 5.5: laravel.com/docs/5.5/blade#switch-statementsXanthippe
@KyleChallis put \ in front of Blade, or put use Blade on top of your file.Dissidence
B
22

IN LARAVEL 5.2 AND UP:

Write your usual code between the opening and closing PHP statements.

@php
switch (x) {
    case 1:
        //code to be executed
        break;
    default:
        //code to be executed
}
@endphp
Barye answered 9/9, 2016 at 14:55 Comment(1)
This @php syntax is very useful in L5.2 >Unemployable
L
7

In Laravel 5.1, this works in a Blade:

<?php
    switch( $machine->disposal ) {
        case 'DISPO': echo 'Send to Property Disposition'; break;
        case 'UNIT':  echo 'Send to Unit'; break;
        case 'CASCADE': echo 'Cascade the machine'; break;
        case 'TBD':   echo 'To Be Determined (TBD)'; break;
    }
?>
Locate answered 2/11, 2016 at 14:16 Comment(0)
E
7

This is now built in Laravel 5.5 https://laravel.com/docs/5.5/blade#switch-statements

Excise answered 20/9, 2017 at 14:12 Comment(0)
A
1

You can extend blade like so:

    Blade::directive('switch', function ($expression) {
        return "<?php switch($expression): ?>";
    });
    Blade::directive('case', function ($expression) {
        return "<?php case $expression: ?>";
    });
    Blade::directive('break', function () {
        return "<?php break; ?>";
    });
    Blade::directive('default', function () {
        return "<?php default: ?>";
    });
    Blade::directive('endswitch', function () {
        return "<?php endswitch; ?>";
    });

You can then use the following:

@switch($test)
@case(1)
        Words
@break
@case(2)
    Other Words
    @break
@default
    Default words
@endswitch

However do note the warnings in : http://php.net/manual/en/control-structures.alternative-syntax.php

If there is any whitespace between the switch(): and the first case then the whole code block will fail. That is a PHP limitation rather than a blade limitation. You may be able to bypass it by forcing the normal syntax e.g.:

Blade::directive('switch', function ($expression) {
    return "<?php switch($expression) { ?>";
});
Blade::directive('endswitch', function ($) {
    return "<?php } ?>";
});

But this feels a bit wrong.

Akin answered 20/6, 2017 at 10:17 Comment(0)
S
0

It's a bit off-topic but for some reason, if the 'cases' are strings, using double quotes as such @case("foo") is not working as expected, in case you're experiencing such a problem, single quotes seem to work, so instead of @case("foo") use @case('foo'). Maybe someone with more information could shed some light on this.

Regards.

Synchrocyclotron answered 30/11, 2021 at 9:4 Comment(0)
N
-2

To overcome the space in 'switch ()', you can use code :

Blade::extend(function($value, $compiler){
    $value = preg_replace('/(\s*)@switch[ ]*\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
    $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
    $value = preg_replace('/(\s*)@case[ ]*\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
    $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
    $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
    return $value;
  });
Narcotize answered 26/6, 2017 at 5:10 Comment(0)
Z
-6

When you start using switch statements within your views, that usually indicate that you can further re-factor your code. Business logic is not meant for views, I would rather suggest you to do the switch statement within your controller and then pass the switch statements outcome to the view.

Zachariahzacharias answered 27/4, 2015 at 14:10 Comment(2)
To be fair, switch statements can certainly belong in the view. For example, if you're setting CSS classes based on data ranges in a table, you wouldn't want to embed display logic in the controller.Lexi
"Business logic is not meant for views,". Business logic is for the visual layer, the logic layer and the persistence layer. Its tedious and redundant but a quality code does that.Hermaphrodite

© 2022 - 2024 — McMap. All rights reserved.