au9500 / laravel-blade-push-once-directive
Blade @pushOnce directive for idempotent stack pushes in Laravel.
Installs: 39
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/au9500/laravel-blade-push-once-directive
Requires
- php: ^8.2
- illuminate/support: ^10.0|^11.0|^12.0
Requires (Dev)
- laravel/pint: ^1.26
- orchestra/testbench: ^10.8
- phpunit/phpunit: ^12.4
README
A lightweight Laravel Blade extension that adds an idempotent @pushOnce directive.
This ensures Blade stack content is pushed only once, even if the directive appears multiple times or inside repeatedly included partials or components.
Prevent duplicate JavaScript, CSS, or inline script blocks effortlessly. β¨
β¨ Features
- π§© Idempotent Blade
@pushOncedirective - π Optional unique key support
- βοΈ Auto-generated key (based on file + line) if none provided
- π Works in partials, components, includes, and layouts
- π« Prevents duplicate pushes completely
- πͺΆ Zero output buffering, fully Blade-native
- π§ͺ Fully tested with PHPUnit + Testbench
- π¦ Minimal and clean implementation
π¦ Installation
composer require au9500/laravel-blade-push-once-directive
Laravel automatically discovers the service provider.
π Usage
πΉ Basic Example
@pushOnce('scripts')
<script src="/js/app.js"></script>@endPushOnce
Even if included many times, this script is pushed only once into the scripts stack.
πΉ With a Custom Key
@pushOnce('styles', 'datepicker')
@endPushOnceEnsures this block is pushed once per request.
πΉ In Partials
resources/views/partials/scripts.blade.php:
@pushOnce('scripts')
<script>console.log('loaded');</script>@endPushOnce
Usage:
@include('partials.scripts')
@include('partials.scripts')
@include('partials.scripts')
Only one script block will appear in the final output. βοΈ
πΉ In Layouts
@stack('scripts')Any @pushOnce('scripts') from child views will be injected here β exactly once.
π How It Works
The directive checks an internal registry:
- If the stack/key combo has not been used yet β the content is pushed normally.
- If it has been used β the entire block is skipped.
No output buffering, no duplicated content, fully compatible with Bladeβs native stack behavior. π§
π§ͺ Running Tests
vendor/bin/phpunit
Included tests:
- Same key twice β only one push
- Different keys β all pushed
- Partials included multiple times β only one push
- Auto-generated default key behavior
- Full HTML rendering through layouts & stacks
π‘ Requirements
- PHP 8.2+
- Laravel 10.x / 11.x / 12.x
π€ Contributing
- Fork the repository
- Create a feature branch
- Commit your changes
- Open a pull request
π License
MIT License.