DEV Community

Mahek
Mahek

Posted on

Level Up Your Laravel Blade Templates with Custom Directives

Custom blade directives

Laravel's Blade templating engine is powerful, but sometimes, you need custom directives to make your templates cleaner and more expressive. In this post, we'll explore several useful custom Blade directives that will simplify your views.


1. Convert Timestamps to Readable Formats (@timestamp)

Handling timestamps in Blade templates can get repetitive. Instead of writing {{ \\Carbon\\Carbon::parse($date)->format('M d, Y h:i A') }} every time, create a custom directive:

use Illuminate\Support\Facades\Blade;
use Carbon\Carbon;

Blade::directive('timestamp', function ($expression) {
    return "<?php echo Carbon::parse($expression)->format('M d, Y h:i A'); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@timestamp($post->created_at)
Enter fullscreen mode Exit fullscreen mode

Output: Mar 05, 2025 10:30 AM


2. Custom Slug Generation with a Dictionary (@slugify)

Sometimes, you want custom slug generation that replaces specific words before creating a slug.

Blade::directive('slugify', function ($expression) {
    return "<?php echo Str::slug(str_replace(['&', '@', '#'], ['and', 'at', 'hash'], $expression)); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@slugify('Hello @world & Laravel!')
Enter fullscreen mode Exit fullscreen mode

Output: hello-at-world-and-laravel


3. Truncate Text to a Fixed Length (@truncate)

To avoid long text overflowing in UI elements, truncate it neatly:

use Illuminate\Support\Str;

Blade::directive('truncate', function ($expression) {
    return "<?php echo Str::limit($expression, 50, '...'); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@truncate($post->content)
Enter fullscreen mode Exit fullscreen mode

4. Convert HTML to Markdown (@markdown)

If you store HTML in the database but want to render it as Markdown:

use Illuminate\Support\Str;

Blade::directive('markdown', function ($expression) {
    return "<?php echo Str::markdown($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@markdown('<h1>Hello World</h1>')
Enter fullscreen mode Exit fullscreen mode

5. Role-Based Access Control Directives (@iseditor, @iscco)

Easily check if a user has a specific role:

Blade::directive('iseditor', function () {
    return "<?php if(auth()->check() && auth()->user()->role === 'editor'): ?>";
});
Blade::directive('endiseditor', function () {
    return "<?php endif; ?>";
});

Blade::directive('iscco', function () {
    return "<?php if(auth()->check() && auth()->user()->role === 'cco'): ?>";
});
Blade::directive('endiscco', function () {
    return "<?php endif; ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@iseditor
    <p>Editor Dashboard</p>
@endiseditor

@iscco
    <p>CCO Access Panel</p>
@endiscco
Enter fullscreen mode Exit fullscreen mode

6. FontAwesome Icons (@fa)

A quick way to include FontAwesome icons in Blade:

Blade::directive('fa', function ($expression) {
            return "<?php echo '<i class=\"fa fa-' . e($expression) . '\"></i>'; ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@fa('home')
Enter fullscreen mode Exit fullscreen mode

Output: <i class="fa fa-home"></i>


7. Convert Links to CDN URLs (@cdn)

Dynamically replace URLs to use a CDN:

Blade::directive('cdn', function ($expression) {
    return "<?php echo str_replace('/storage/', 'https://cdn.example.com/', $expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

<img src="@cdn($user->avatar)">
Enter fullscreen mode Exit fullscreen mode

8. Remove HTML Tags from a String (@stripTags)

Sanitize input by stripping unwanted HTML tags:

Blade::directive('stripTags', function ($expression) {
    return "<?php echo strip_tags($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@stripTags($post->content)
Enter fullscreen mode Exit fullscreen mode

9. Base64 Encode/Decode Data (@base64, @base64decode)

Encoding:

Blade::directive('base64', function ($expression) {
    return "<?php echo base64_encode($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Decoding:

Blade::directive('base64decode', function ($expression) {
    return "<?php echo base64_decode($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@base64('Hello World')
@base64decode('SGVsbG8gV29ybGQ=')
Enter fullscreen mode Exit fullscreen mode

10. Word & Character Count (@wordCount, @charCount)

Word count:

Blade::directive('wordCount', function ($expression) {
    return "<?php echo str_word_count($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Character count:

Blade::directive('charCount', function ($expression) {
    return "<?php echo strlen($expression); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@wordCount($post->content)
@charCount($comment->text)
Enter fullscreen mode Exit fullscreen mode

11. Human-Readable Timestamps (@ago)

Convert timestamps into x minutes/hours ago format:

Blade::directive('ago', function ($expression) {
    return "<?php echo Carbon::parse($expression)->diffForHumans(); ?>";
});
Enter fullscreen mode Exit fullscreen mode

Usage:

@ago($post->created_at)
Enter fullscreen mode Exit fullscreen mode

Output: 2 hours ago


Conclusion

Using custom Blade directives makes your Laravel views more readable and efficient. Whether you need text formatting, role-based access control, or CDN optimization, these directives will streamline your development workflow.

Connect with on X(Twitter) to find more interesting topics like this.
Got more ideas? Share your favorite Blade directives in the comments! ๐Ÿš€

Top comments (1)

Collapse
 
xwero profile image
david duymelinck • Edited

When i see those directives it looks like the variables aren't transformed to their actual display values in the controller.
The main benefit of transforming the variables before they reach the template is that in case of problems a solution can be added. For example in the case of a Carbon parse failure an empty string can be added. The template is the last in the chain.
Another benefit is that the display values can be changed by code. This is how in CMS solutions it is possible to change the date format when the editor wants to change the display.

For the if example, Blade has an if method.

<?php
Blade::directive('iseditor', function () {
    return "<?php if(auth()->check() && auth()->user()->role === 'editor'): ?>";
});
Blade::directive('endiseditor', function () {
    return "<?php endif; ?>";
});
// versus

Blade::if('iseditor', fn() => auth()->check() && auth()->user()->role === 'editor';);
Enter fullscreen mode Exit fullscreen mode

But even better is to use a gate. Then you can use the can directive.

While the directive method is a nice tool, it should only be used when it is needed.