Custom @blade directives for your views.

Blade Directives in Laravel offer a clean way to include content dynamically within your views, which also improves the readability an...

Karan Datwani
Karan Datwani
Share:

Blade Directives in Laravel offer a clean way to include content dynamically within your views, which also improves the readability and maintainability of our blade views.

What is a Blade Directive?

Most calls you see in blade files that start with @ are called blade directives. Behind the scenes, they will call a PHP function to do something, without having to write <?php and ?> code blocks in the blade file.

What's the benefit of using Blade Directives?

By using blade directives for commonly used functions, you will make your blade files cleaner, easier to read, and easier to maintain. Here's a quick example to make my point:

<?php if (Auth::check()) { ?>
 <a href="/account/info">My Account</a>
<?php } ?>

// VS.

@auth
 <a href="/account/info">My Account</a>
@endauth

Basic Blade Directives

Before we dive into creating custom directives, let’s explore some of the built-in Blade directives that Laravel provides. A few of the common directives are:

Directive Purpose Example
@if, @else Conditional logic @if($condition) ... @else ... @endif
@foreach Loop through arrays @foreach($array as $item) ... @endforeach
@include Include partials @include('partials.header')
@extends Extend a layout @extends('layouts.master')
@section, @endsection Define content sections @section('content') ... @endsection
@csrf Add CSRF token <form> @csrf </form>
@auth, @guest Check authentication status @auth ... @endauth

But what if our requirement is something different? In such cases, we can easily create and use our custom blade directive. You write code once and use it multiple times.

How to create custom blade directives?

Creating custom blade directives is quite simple. Write the directive code inside the boot() function of AppServiceProvider:

public function boot(){

    Blade::directive('website_link', function () {
        $app_url = url(config('app.url'));
        return "<a target='_blank' href='$app_url'>$app_url</a>";
    });
}

And that's it 🎉. You are now equipped with your custom directive. Simply use the blade template by calling the name of the directive:

<div>
    @website_link()
</div>

Let's see a more realistic example.

I use it for my E-commerce app, where I utilize Matomo analytics device-detector package to detect devices in my laravel app. I preferred creating a few directives and using them like this:

<div>    
    @mobile()
        <p>Mobile view</p>
    @endmobile
    
    @tablet()
        <p>Tablet view</p>
    @endtablet
    
    @desktop()
        <p>Desktop view</p>
    @enddesktop
</div>

I planned to create many directives, but no one would like to keep all of them in AppServiceProvider. I prefer to group directives by category or type into separate files. For this:

- Step 1: I created a file app/Helpers/MatomoDirectives.php to house all device detection directives.

<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Blade;
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;

class MatomoDirectives
{
    public static function register()
    {
        if (!app()->runningInConsole()) {
            
            $dd = new DeviceDetector($_SERVER['HTTP_USER_AGENT'], ClientHints::factory($_SERVER));
            $dd->setCache(new \DeviceDetector\Cache\LaravelCache());
            $dd->parse();
            
            
            // notice "if" here, it's a conditional directive
            Blade::if('tablet', function () use ($dd) {
                return $dd->isTablet();
            });

            Blade::if('mobile', function () use ($dd) {
                return ($dd->isSmartphone() || $dd->isPhablet() || $dd->isFeaturePhone());
            });

            Blade::if('desktop', function () use ($dd) {
                return !($dd->isSmartphone() || $dd->isPhablet() || $dd->isFeaturePhone() || $dd->isTablet());
            });
            
        }
    }
}

- Step 2: Registered the file in AppServiceProvider:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\MatomoDirectives;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        BladeDirectives::register();
    }
}

Easy peasy!

Conclusion

In this tutorial, we learn to create our own laravel blade directives. Blade directives can make our views cleaner and more readable and streamline our development process. Give it a try; if you love it, share it with others. ❤️

Want to receive more articles like this?

Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.

Reactions & Comments

What do you think about this?

Latest Articles

Wondering what our community has been up to?