Laravel 5.5 new feature - Custom Blade::if Directives with example

Laravel 5.5 new feature - Custom Blade::if Directives with example

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.

AppServiceProvider

Here in this class, We will write a logic to check the apps environment inside the boot method :

app/Providers/AppServiceProvider.php
  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\ServiceProvider;
  4. use Illuminate\Support\Facades\Blade;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Bootstrap any application services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. Blade::if('env', function ($env) {
  15. return app()->environment($env);
  16. });
  17. }
  18. /**
  19. * Register any application services.
  20. *
  21. * @return void
  22. */
  23. public function register()
  24. {
  25. }
  26. }
Welcome view

Now open your welcome.blade.php file to use your new blade directive in following way :

resources/views/welcome.blade.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Laravel 5.5 new feature</title>
  5. <meta charset="utf-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. </head>
  9. <body>
  10. @env('local')
  11. You are in the local environment..
  12. @endenv
  13. </body>
  14. </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.

  1. \Blade::if('is_subscribed', function () {
  2. return auth()->check() && auth()->user()->isSubscribed();
  3. });

Use this new directive in template :

  1. @is_subscribed
  2. User is Subscribed.
  3. @else
  4. User is not Subscribed.
  5. @endis_subscribed

Phone: (+91) 8800417876
Noida, 201301