Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Blade stringable to handle objects centrally in Laravel 8.x

Wouldn’t it be useful if you could define a certain action that should be performed every time your Blade templates encounter objects of a specific class?

So, for instance, let’s say when working with libraries such as Carbon, it’s often the case where you would want to format it in a certain way throughout your application.

Normally, if you want to format the date in a specific format for a Carbon instance, you could do it in Blade templates like so.

{{ $post->created_at->format('d-m-Y') }}

This is fine. But as you can tell, you would find yourself repeating the same at other places in your application as well. When all you’d want is to format it similarly everywhere where the Carbon instance is found in your Blade templates.

This PR for Laravel 8.x tries to solve this very problem.

Blade Stringable

As it turned out, this PR introduces a new Blade::stringable() method that can be placed in the boot method of a Service Provider and allows the user to add intercepting closures for any class. The returned value will be outputted in Blade.

So, if we want every Carbon object found in Blade templates to be formatted in a certain way, we can define it in the boot method of the App\Providers\AppServiceProvider like so.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Blade::stringable(Carbon::class, function ($object) {
            return $object->format('d-m-Y');
        });
    }
}

Once done, you don’t need to format the Carbon based dates in your application manually. The specified format in the Blade::stringable will be applied to every available Carbon date in your application.

Pretty handy, right?

You can apply this to just about any class/library where you want some uniformity throughout your application.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?