Creating custom blade directives in Laravel 5

Laravel-Nepal
Sep 5, 2018 · 3 min read

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 .

<?php
if (! empty($examples)) {
foreach ($examples as $data ) {
?>
<li> <?= $data->name ?> </li>
<?php
}
else {
?>
<p> No data found </p>
<?php
}
?>

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

@forelse ($examples as $data)
<li> {{ $data->name }} </li>
@empty
<p> No data found </p>
@endforelse

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.

@website('site-name')
// Laravel-Nepal
@website('site-description')
// Laravel-Nepal, a group of developers from Nepal sharing knowledge about Laravel.

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.

<?php namespace App\Providers;use Illuminate\Support\ServiceProvider;class BladeServiceProvider extends ServiceProvider {      /**
* Bootstrap any application services.
*
* @return string
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

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 .

<?php/*** Custom blade directive Helper functions*/if (! function_exists('website')) :      function website(string $key) {            return config('website.'.$key);      }endif;

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 .

<?php/*** Website configurations* @version 0.1.0*/return [     'site-name' => env('APP_NAME', 'Laravel-Nepal'),     'site-description' => 'Laravel-Nepal, a group of developer\'s from Nepal sharing knowledge about Laravel.'];

Step 4: Defining our directive

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

<?php namespace App\Providers;use Illuminate\Support\ServiceProvider;class BladeServiceProvider extends ServiceProvider {/**
* Bootstrap any application services.
*
* @return string
*/
public function boot()
{
/** Website */
Blade::directive('website', function ($key) {
return "<?php echo website($key); ?>";
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

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

'providers' => [
// Other Service Providers
App\Providers\BladeServiceProvider::class,
],

Testing

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

@website('site-name')
// Laravel-Nepal
@website('site-description')
// Laravel-Nepal, a group of developers from Nepal sharing knowledge about Laravel.

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 drop in your comment. This article is published at laravel-nepal.com .

Happy coding 🙂

Laravel-Nepal

Written by

We share what we learn . Articles and tutorials from laravel developers of Nepal.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade