Creating custom blade directives in Laravel 5

directive-laravel-nepal

Introduction

Blade is a great template engine, simple yet powerful . If you know Laravel framework,  you already know how great is Laravel Blade and it’s syntax .  In our daily work, often we found our self writing complex logic and conditions in our Blade . This makes our pretty blade template looks messy and may be unmanageable . Here comes blade directive to the rescue .

Getting Started

Today, we will learn what exactly is Blade Directive and how they can be useful for making your template readable and clean. Let’s get started 🙂

Laravel provides many blade directive like @foreach , @isset, @empty, @auth, @guest and many others . Let’s take a look at simple demonstration .

The above code seems alright but looks messy . In Laravel , we can use @forelse directive which is more readable and cleaner .

This code looks fun and more readable right ? 🙂 Blade directives let you hide the messy logic and conditions in your views . Let’s create a custom directive which may come handy in our next projects .

We will create a custom directive which will return our website name, logo or any other entity . The final result will be like this.

Step 1 : Creating service provider

Run the command in terminal , php artisan make:provider BladeServiceProvider . This will create BladeServiceProvider . In this provider , we will define our directive . The generated class will look like this.

<!–RndAds–>

Step 2 : Define a helper file

We will create our own helper file which will return values according to the key . Let’s create a helper file and functions . If you don’t know to create your own custom helper functions, we have a article about it . creating your own helper files  , after that let’s create a function .

This function will return the value from config file (website.php) according to the given key . We know what to do next right ? 🙂

Step 3 : Creating a config file

Create a config file in app/config . Let’s write some dummy data in our config file website.php .

Step 4: Defining our directive

In this step, we will define our directive in your service provider (app/http/providers).

Lastly, let’s register our service provider in our config/app.php file .

Testing

First clear our views using command , php artisan view:clear and use the directives .

Conclusion

This is just a simple directive but you can play around with this directive and make your own  . We have covered a lot of topic in this article . Hope this help you understand the basic concept of directive and let you create your own .

A list of todos you can do :

  1. Exception handling if key not found / return null
  2. Adding more keys
  3. Instead of config values , retrieve values from database

If you have any queries or suggestions for us, feel free to contact us here.

Happy coding 🙂

Sharing is caring!

Related Post