In this tutorial, I will tell you the new features custom Blade::if
directives added with Laravel 5.5 with example.
Sometime you write same if condition everywhere in the view but now you do not write same if condition many time by using new feature Blade::if
directive of Laravel 5.5.
Laravel 5.5 Blade::if make it more convenient to abstract repetitive checks out of templates and making them cleaner and more readable.
There is a boot method inside the AppServiceProvider
class to write your logic for blade if directive.
Here in this class, We will write a logic to check the apps environment inside the boot method :
app/Providers/AppServiceProvider.php
- <?php
- namespace App\Providers;
- use Illuminate\Support\ServiceProvider;
- use Illuminate\Support\Facades\Blade;
- class AppServiceProvider extends ServiceProvider
- {
- /**
- * Bootstrap any application services.
- *
- * @return void
- */
- public function boot()
- {
- Blade::if('env', function ($env) {
- return app()->environment($env);
- });
- }
- /**
- * Register any application services.
- *
- * @return void
- */
- public function register()
- {
- }
- }
Now open your welcome.blade.php
file to use your new blade directive in following way :
- <!DOCTYPE html>
- <html>
- <head>
- <title>Laravel 5.5 new feature</title>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- </head>
- <body>
- @env('local')
- You are in the local environment..
- @endenv
- </body>
- </html>
There are also some other example to understand the concept of Blade::if directive.
Let's have a another example to check if user is subscribed or not.
- \Blade::if('is_subscribed', function () {
- return auth()->check() && auth()->user()->isSubscribed();
- });
Use this new directive in template :
- @is_subscribed
- User is Subscribed.
- @else
- User is not Subscribed.
- @endis_subscribed