Looking to hire Laravel developers? Try LaraJobs

laravel-blade-push-once-directive maintained by au9500

Description
Blade @pushOnce directive for idempotent stack pushes in Laravel.
Author
Andreas Uretschnig
Last update
2026/01/13 16:03 (dev-main)
License
Links
Downloads
45

Comments
comments powered by Disqus

🚀 Laravel Blade PushOnce Directive

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 @pushOnce directive
  • 🔑 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')

@endPushOnce

Even if included many times, this script is pushed only once into the scripts stack.


🔹 With a Custom Key

@pushOnce('styles', 'datepicker')

Ensures this block is pushed once per request.


🔹 In Partials

resources/views/partials/scripts.blade.php:

@pushOnce('scripts')

@endPushOnce

Usage:

@include('partials.scripts')
@include('partials.scripts')
@include('partials.scripts')

Only one script block will appear in the final output. ✔️


🔹 In Layouts

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

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Open a pull request

📄 License

MIT License.