Switch in Laravel 5 - Blade
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
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~
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
This is now built in Laravel 5.5 https://laravel.com/docs/5.5/blade#switch-statements