Skip to content

Instantly share code, notes, and snippets.

@sujalpatel2209
Last active July 19, 2017 16:29
Show Gist options
  • Save sujalpatel2209/af7581f767918a32461a091be820c52b to your computer and use it in GitHub Desktop.
Save sujalpatel2209/af7581f767918a32461a091be820c52b to your computer and use it in GitHub Desktop.
Using Switch Case on Laravel 5.x Blade
In this post I will show you about how to add Switch Case to Laravel 5.x blade template engine.
On app/Providers/AppServiceProvider.php do following steps:
use Illuminate\Support\Facades\Blade;
On function function boot() add following line:
// Switch case directive
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;
});
And now you can use following blade notation to make switch case condition.
@switch($k)
@case(0)
// Code
@breakswitch
@case(1)
// Code
@breakswitch
@case(2)
// Code
@breakswitch
@endswitch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment