Custom Blade Directives in Laravel

Blade::directive(‘datetime’, function ($expression) {
return “<?php echo ($expression)->format(‘jS M, Y’); ?>”;
});
@directive($post->created_at)
Blade::directive(‘padLeft’, function ($expression) {
return “<?php echo Str::of($expression)->padLeft(10, ‘-’) ?>”;
});
@padLeft($post->type)
Blade::if(‘PaidSubscriber’, function () {
//Some Logic which returns boolean
});
@PaidSubscriber
Display Paid Content Here.
@else
Subscribe to our Plans to access Paid Content.
@endPaidSubscriber
Blade::if(‘PaidSubscriber’, function () {
if ($user = auth()->user()) { //If Logged In
if ($user->subscriber == 1) { //If Subscriber.
return true;
}
}
return false;
});
<?php
namespace App\Http\Traits;
use Illuminate\Support\Facades\Blade;trait BladeDirectives
{
public function setupCustomDirectives()
{
Blade::directive('datetime', function ($expression) {
return "<?php echo ($expression)->format('jS M, Y'); ?>";
});
Blade::directive('padL', function ($expression) {
return "<?php echo Str::of($expression)->padLeft(10, '-') ?>";
});
Blade::if('PaidSubscriber', function () {
if ($user = auth()->user()) {
if ($user->subscriber == 2) {
return true;
}
}
return false;
});
}
}
use App\Http\Traits\BladeDirectives;class AppServiceProvider extends ServiceProvider
{
.
.
.
public function boot()
{
//
$this->setupCustomDirectives();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store