Build your OWN switch statment using Laravel’s custom blade directives

One of the good points of Laravel’s framework is that it allows you to make your own components, macros and directives. so today we will make use of Laravel’s Custom Blade directives and make something good.

The Hello world example

Our very first example will be to print something like Hello Name. we will use this code in our view

@hello('Houssin')

and let’s jump to the boot method of the AppServiceProvider to define how we will render that line of code, Of course do not foreget to import the Blade facade.

Blade::directive('hello', function($name){
return "<?php echo 'Hello '.{$name}; ?>";
});

easy isn’t?

Switch directive

Our second example will be the very famous switch case controller, I think its not defined yet … at least according to my experience with Laravel.

1- Now we will start by setting up the bases of the switch case, something like

@switch($var)
@endswitch

so basically is nothing but those lines of code

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

2- the case and break part, the case directive accepts a parameter to compare with the variable already passed to the swtich. and the break all it does is printing the break; statement.

Blade::directive('case', function($value){
return "<?php case {$value}: ?>";
});
Blade::directive('breakcase', function(){
return "<?php break; ?>";
});

3- the default part, or let’s call it the whatever part, to avoid conflicts.

Blade::directive('whatever', function(){
return "<?php default : ?>";
});

So let us use all of them

we assume we have passed $num to the view.

@switch($num)
@case(10)
<h1>its 10</h1>
@breakcase

@case(20)
<h1>its 20</h1>
@breakcase

@whatever
<h1>not specified</h1>
@endswitch

Actually, yes it won’t work, why? its simple because its not allowed to use any code between the switch and the first case, but we are not doing it?

well we do, the space when using template engin even the space is replaced with a <?php echo ‘ ‘ ?>

so let us tweak our code …. How? we will not end our switch directive, that way everything after it will be ignored.

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

and make a special case called ‘firstcase’ … just like that

Blade::directive('firstcase', function($value){
return "case {$value}: ?>";
});

and Now our code should be like that

@switch($num)
@firstcase(10)
<h1>its 10</h1>
@breakcase

@case(20)
<h1>its 20</h1>
@breakcase

@whatever
<h1>not specified</h1>
@endswitch