@pushonce Blade directive

Submitted by laraning - 6 years ago

What if you want to use the @push blade directive but you don't want it to push twice the same content? For example, if you have a UI component that loads JS files and you want to reuse that component in the same view, so without this trick it will load twice your JS code from your different UI components.

In your Service Provider PHP file, boot() method:

Blade::directive('pushonce', function ($expression) {
    $var = '$__env->{"__pushonce_" . md5(__FILE__ . ":" . __LINE__)}';

    return "<?php if(!isset({$var})): {$var} = true; \$__env->startPush({$expression}); ?>";
});

Blade::directive('endpushonce', function ($expression) {
    return '<?php $__env->stopPush(); endif; ?>';
});


Cheers!

Bruno Falcão
www.laraning.com
@_laraning